Autofac Registration Completed - Integration Tests with DI

I write integration tests for my application and use a container for this. I want to be able to register all components, as I do in real time, and then override some components and switch them to use stub implementations.

I would not want to share DI and have a container for tests just because I want to check the real thing.

Doing this also seems ugly:

public class MyRegistrations { public static RegisterAll(bool isInTest= false) { if (isTest) { // Register test fakes } else // Register real components } } 

So I thought about the basic registrations in my test environment. How to do it?

Other best ways to achieve my goal?

thanks

+5
source share
2 answers

Autofac will use the last registered component as the default provider of this service

From an AutoFac document.

In your arr / setup / testInit factor, register mocks, then enable SUT:

 [SetUp] public void TestInit() { Mock<IFoo> mock = new Mock<IFoo>(); builder.RegisterInstance(mock.object).As<IFoo>(); ... ... _target = builder.Resolve<The component>(); } 

Note:

Singlets, static elements and SingletonLifestyle (registration) can cause some problems ....

+2
source

Well, for example, you can create a static action method inside your composition root to change the current configuration and invoke it during testing. For instance:

 public class CompositionRoot { public static Action<IContainer> OverrideContainer = c => { }; internal static IContainer CreateContainer() { ContainerBuilder builder = new ContainerBuilder(); /// etc. etc. var container = builder.Build(); OverrideContainer(container); return container; } } 

After that, you can create the layout of your server, for example, as follows:

 [TestFixture] public class ConfigurationControllerFixture : BaseServer { [Test] public async Task verify_should_get_data() { var response = await GetAsync(Uri); Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); } protected override string Uri { get { return "api/configuration"; } } } public abstract class BaseServer { protected TestServer Server; protected abstract string Uri { get; } protected virtual void OverrideConfiguration() { CompositionRoot.OverrideContainer = c => { // new autofac configuration cb.Update(c); }; AppStartup.OverrideConfiguration = c => { // same as explained, but for HttpConfiguration }; } } [SetUp] public void Setup() { OverrideConfiguration(); Server = Microsoft.Owin.Testing.TestServer.Create(app => { var startup = new AppStartup(); startup.Configuration(app); }); PostSetup(Server); } 

Hope this helps :)

+1
source

Source: https://habr.com/ru/post/1246611/


All Articles