Mocking and resolving Autofac dependency in integration test in AspNetCore with TestServer

谁说胖子不能爱 提交于 2019-12-12 12:19:17

问题


I'm using AspNetCore 2.2 Following (moreless) the docs here: https://docs.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-2.2

I am using Autofac, my Startup class has the following methods:

public void ConfigureServices(IServiceCollection services)
public void ConfigureContainer(ContainerBuilder containerBuilder) //this is where things can be registered directly with autofac and runs after ConfigureServices
public void Configure(...) //the method called by runtime

The way I use Autofac, as recommended by its docs, is by having Program.cs like this

public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseKestrel()
            .ConfigureServices(services => services.AddAutofac())
            .UseIISIntegration()
            .UseStartup<Startup>()
            .ConfigureAppConfiguration((builderContext, config) =>
            {
                var env = builderContext.HostingEnvironment;
                config
                    .AddJsonFile("appsettings.json", false, true)
                    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", true, true)
                    .AddEnvironmentVariables();
            });
}

I am now using TestServer for my test project where I want to use the real Startup class. But I would like to modify one of the dependencies.

I have seen that there is a method available on WebHostBuilder to .ConfigureTestServices(services => {});

so I tried the following:

public abstract class ComponentTestFeature
    : Feature
{
    protected HttpClient HttpClient { get; }

    protected ComponentTestFeature()
    {
        var configuration =
            new ConfigurationBuilder()
                .AddJsonFile("appsettings.Test.json")
                .Build();

        var webHostBuilder =
            new WebHostBuilder()
                .ConfigureServices(services => services.AddAutofac())
                .ConfigureTestServices(services =>
                {
                    services.AddScoped<IEventStoreManager, MockEventStoreManager>();
                })
                .UseConfiguration(configuration)
                .UseStartup<Startup>();

        var server = new TestServer(webHostBuilder);
        HttpClient = server.CreateClient();
        var myService = server.Host.Services.GetRequiredService<IEventStoreManager>();
    }
}

As you can see I want to use a MockEventStoreManager implementation for IEventStoreManager so that this is the implementation that should be resolved by the container. However this is not working as expected and myService resolved is the original implementation, the real one, not the mock one.

Does anybody know how could I achieve what I want?

UPDATE 1: After more investigation I had to create an issue on github AspNetCore because the extension method is executed before the ConfigureContainer, therefore I cannot really override autofac dependencies nor retrieve autofac container later on. https://github.com/aspnet/AspNetCore/issues/6522

UPDATE 2: Just FYI, this is how the Startup.cs looks like. As you can see all the dependencies but mvc are registered in autofac's container.

public void ConfigureServices(IServiceCollection services)
{
    services
        .AddMvc()
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}

// This is where things can be registered directly with autofac and runs after ConfigureServices, so it will override it
public void ConfigureContainer(ContainerBuilder builder)
{
    builder.RegisterType<EventStoreManager>().As<IEventStoreManager>();
}

and what I want to do is to use MockEventStoreManager implementation for IEventStoreManager in my tests, so I need to override (from my test project) that Autofac's registration in a nice way.


回答1:


Register the mocked implementation with the container builder for the test using ConfigureTestContainer

//...
.ConfigureServices(services => services.AddAutofac())
.ConfigureTestContainer<ContainerBuilder>(builder => {
    builder.RegisterType<MockEventStoreManager>().As<IEventStoreManager>();
})
//...

This should avoid getting the actual implementation that is added by Startup.ConfigureContainer as

If more than one component exposes the same service, Autofac will use the last registered component as the default provider of that service:

Reference Default Registrations

ConfigureTestContainer is invoked after the Startup.ConfigureContainer so the last registration with the mock would be the default provider of the service.




回答2:


There are a couple of options:

  • Have a custom implementation of your dependency in your testserver project

  • Implement and manually register a mocked implementation of your dependency with a nugget like "Moq"



来源:https://stackoverflow.com/questions/54107886/mocking-and-resolving-autofac-dependency-in-integration-test-in-aspnetcore-with

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!