Search code examples
c#unit-testingdependency-injectionintegration-testingautofac

Override Autofac registration - Integration tests with DI


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

I wouldn't want to seperate the DI and have a container for tests only because I want to test 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 of overriding registrations in my test enviorment. How should it be done?

Any other better ways for achieving my goal?

Thanks


Solution

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

    From the AutoFac documation.

    In your arrange/setup/testInit phase register the mocks, then resolve the SUT:

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

    Note:

    Singletons, static members and SingletonLifestyle(registration) may cause some troubles....