Search code examples
c#.net.net-7.0

net 7 integration tests - test specific ConfigureTestServices?


I'm using ConfigureTestServices to mock out some of my dependencies for integration tests. Works fine. But I would like to have different mocks of IFileSystem for different tests, how can I replace it on test level? I still want to utilize the IoC container.

public class CustomWebApplicationFactory : WebApplicationFactory<Program>
{
    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder.ConfigureTestServices(services =>
        {
            var fileSystemMock = new Mock<IFileSystem>();
            // fileSystemMock.Setup...
            services.AddScoped<IFileSystem>(_ => fileSystemMock.Object);
        });
    }
}

Here's my test:

public class MyTests
{
        private CustomWebApplicationFactory _factory = null!;
        private IServiceScope _scope = null!;
    
        [SetUp]
        public void Setup()
        {
            _factory = new CustomWebApplicationFactory();
            _scope = _factory.Services.CreateScope();
        }

        [TearDown]
        public void Dispose()
        {
            _factory.Dispose();
            _scope.Dispose();
        }


        [Test]
        public void Test1()
        {
            // ClassToTest has IFileSystem injected
            // How can I add a test specific mock of it for this test?
            var service = _scope.ServiceProvider.GetService<ClassToTest>();
            Assert.IsTrue(true);
        }
}

Solution

  • There are multiple ways this problem can be solved and here are a few examples:

    1. Injecting the IFileSystem mock as a constructor parameter
    2. Resolving the registered IFileSystem using IServiceProvider and setting it up using Mock.Get(fileSystemInstance).Setup(...)
    3. Using CustomWebApplicationFactory as a base class for the tests and making the ConfigureTestServices call overridable