Skip to main content

2 posts tagged with "configuretestcontainer"

View All Tags

Autofac 6, integration tests and .NET generic hosting

I blogged a little while ago around to support integration tests using Autofac. This was specific to Autofac but documented a workaround for a long standing issue with ConfigureTestContainer that was introduced into .NET core 3.0 which affects all third-party containers that use ConfigureTestContainer in their tests.

I'll not repeat the contents of the previous post - it all still stands. However, with Autofac 6 the approach documented there will cease to work. This is because the previous approach relied upon ContainerBuilder not being sealed. As of Autofac 6 it is.

Happily the tremendous Alistair Evans came up with an alternative approach which is listed below:

/// <summary>
/// Based upon https://github.com/dotnet/AspNetCore.Docs/tree/master/aspnetcore/test/integration-tests/samples/3.x/IntegrationTestsSample
/// </summary>
/// <typeparam name="TStartup"></typeparam>
public class AutofacWebApplicationFactory<TStartup> : WebApplicationFactory<TStartup> where TStartup : class
{
protected override IHost CreateHost(IHostBuilder builder)
{
builder.UseServiceProviderFactory<ContainerBuilder>(new CustomServiceProviderFactory());
return base.CreateHost(builder);
}
}
/// <summary>
/// Based upon https://github.com/dotnet/aspnetcore/issues/14907#issuecomment-620750841 - only necessary because of an issue in ASP.NET Core
/// </summary>
public class CustomServiceProviderFactory : IServiceProviderFactory<ContainerBuilder>
{
private AutofacServiceProviderFactory _wrapped;
private IServiceCollection _services;
public CustomServiceProviderFactory()
{
_wrapped = new AutofacServiceProviderFactory();
}
public ContainerBuilder CreateBuilder(IServiceCollection services)
{
// Store the services for later.
_services = services;
return _wrapped.CreateBuilder(services);
}
public IServiceProvider CreateServiceProvider(ContainerBuilder containerBuilder)
{
var sp = _services.BuildServiceProvider();
#pragma warning disable CS0612 // Type or member is obsolete
var filters = sp.GetRequiredService<IEnumerable<IStartupConfigureContainerFilter<ContainerBuilder>>>();
#pragma warning restore CS0612 // Type or member is obsolete
foreach (var filter in filters)
{
filter.ConfigureContainer(b => { })(containerBuilder);
}
return _wrapped.CreateServiceProvider(containerBuilder);
}
}

Using this in place of the previous approach should allow you continue running your integration tests with Autofac 6. Thanks Alistair!

Concern for third-party containers#

Whilst this gets us back up and running, Alistair pointed out that this approach depends upon a deprecated interface. This is the IStartupConfigureContainerFilter which has been marked as Obsolete since mid 2019. What this means is, at some point, this approach will stop working.

The marvellous David Fowler has said that ConfigureTestContainer issue should be resolved in .NET. However it's worth noting that this has been an issue since .NET Core 3 shipped and unfortunately the wonderful Chris Ross has advised that it's not likely to be fixed for .NET 5.

I'm very keen this does get resolved in .NET. Building tests upon an Obsolete attribute doesn't fill me with confidence. I'm a long time user of Autofac and I'd like to continue to be. Here's hoping that's made possible by a fix landing in .NET. If this is something you care about, it may be worth upvoting / commenting on the issue in GitHub so the team are aware of desire around this being resolved.

Autofac, WebApplicationFactory and integration tests

Updated 2nd Oct 2020: for an approach that works with Autofac 6 see this post.


This is one of those occasions where I'm not writing up my own work so much as my discovery after in depth googling.

Integration tests with ASP.NET Core are the best. They spin up an in memory version of your application and let you fire requests at it. They've gone through a number of iterations since ASP.NET Core has been around. You may also be familiar with the TestServer approach of earlier versions. For some time, the advised approach has been using <a href="https://docs.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-3.1#basic-tests-with-the-default-webapplicationfactory">WebApplicationFactory</a>.

What makes this approach particularly useful / powerful is that you can swap out dependencies of your running app with fakes / stubs etc. Just like unit tests! But potentially more useful because they run your whole app and hence give you a greater degree of confidence. What does this mean? Well, imagine you changed a piece of middleware in your application; this could potentially break functionality. Unit tests would probably not reveal this. Integration tests would.

There is a fly in the ointment. A hair in the gazpacho. ASP.NET Core ships with dependency injection in the box. It has its own Inversion of Control container which is perfectly fine. However, many people are accustomed to using other IOC containers such as Autofac.

What's the problem? Well, swapping out dependencies registered using ASP.NET Core's IOC requires using a hook called ConfigureTestServices. There's an equivalent hook for swapping out services registered using a custom IOC container: ConfigureTestContainer. Unfortunately, there is a bug in ASP.NET Core as of version 3.0: When using GenericHost, in tests ConfigureTestContainer is not executed

This means you cannot swap out dependencies that have been registered with Autofac and the like. According to the tremendous David Fowler of the ASP.NET team, this will hopefully be resolved.

In the meantime, there's a workaround thanks to various commenters on the thread. Instead of using WebApplicationFactory directly, subclass it and create a custom AutofacWebApplicationFactory (the name is not important). This custom class overrides the behavior of ConfigureServices and CreateHost with a CustomServiceProviderFactory:

namespace My.Web.Tests.Helpers {
/// <summary>
/// Based upon https://github.com/dotnet/AspNetCore.Docs/tree/master/aspnetcore/test/integration-tests/samples/3.x/IntegrationTestsSample
/// </summary>
/// <typeparam name="TStartup"></typeparam>
public class AutofacWebApplicationFactory<TStartup> : WebApplicationFactory<TStartup> where TStartup : class {
protected override void ConfigureWebHost(IWebHostBuilder builder) {
builder.ConfigureServices(services => {
services.AddSingleton<IAuthorizationHandler>(new PassThroughPermissionedRolesHandler());
})
.ConfigureTestServices(services => {
}).ConfigureTestContainer<Autofac.ContainerBuilder>(builder => {
// called after Startup.ConfigureContainer
});
}
protected override IHost CreateHost(IHostBuilder builder) {
builder.UseServiceProviderFactory(new CustomServiceProviderFactory());
return base.CreateHost(builder);
}
}
/// <summary>
/// Based upon https://github.com/dotnet/aspnetcore/issues/14907#issuecomment-620750841 - only necessary because of an issue in ASP.NET Core
/// </summary>
public class CustomServiceProviderFactory : IServiceProviderFactory<CustomContainerBuilder> {
public CustomContainerBuilder CreateBuilder(IServiceCollection services) => new CustomContainerBuilder(services);
public IServiceProvider CreateServiceProvider(CustomContainerBuilder containerBuilder) =>
new AutofacServiceProvider(containerBuilder.CustomBuild());
}
public class CustomContainerBuilder : Autofac.ContainerBuilder {
private readonly IServiceCollection services;
public CustomContainerBuilder(IServiceCollection services) {
this.services = services;
this.Populate(services);
}
public Autofac.IContainer CustomBuild() {
var sp = this.services.BuildServiceProvider();
#pragma warning disable CS0612 // Type or member is obsolete
var filters = sp.GetRequiredService<IEnumerable<IStartupConfigureContainerFilter<Autofac.ContainerBuilder>>>();
#pragma warning restore CS0612 // Type or member is obsolete
foreach (var filter in filters) {
filter.ConfigureContainer(b => { }) (this);
}
return this.Build();
}
}
}

I'm going to level with you; I don't understand all of this code. I'm not au fait with the inner workings of ASP.NET Core or Autofac but I can tell you what this allows. With this custom WebApplicationFactory in play you get ConfigureTestContainer back in the mix! You get to write code like this:

using System;
using System.Net;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using FakeItEasy;
using FluentAssertions;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
using Microsoft.Extensions.Options;
using Autofac;
using System.Net.Http;
using Newtonsoft.Json;
namespace My.Web.Tests.Controllers
{
public class MyControllerTests : IClassFixture<AutofacWebApplicationFactory<My.Web.Startup>> {
private readonly AutofacWebApplicationFactory<My.Web.Startup> _factory;
public MyControllerTests(
AutofacWebApplicationFactory<My.Web.Startup> factory
) {
_factory = factory;
}
[Fact]
public async Task My() {
var fakeSomethingService = A.Fake<IMySomethingService>();
var fakeConfig = Options.Create(new MyConfiguration {
SomeConfig = "Important thing",
OtherConfigMaybeAnEmailAddress = "[email protected]"
});
A.CallTo(() => fakeSomethingService.DoSomething(A<string>.Ignored))
.Returns(Task.FromResult(true));
void ConfigureTestServices(IServiceCollection services) {
services.AddSingleton(fakeConfig);
}
void ConfigureTestContainer(ContainerBuilder builder) {
builder.RegisterInstance(fakeSomethingService);
}
var client = _factory
.WithWebHostBuilder(builder => {
builder.ConfigureTestServices(ConfigureTestServices);
builder.ConfigureTestContainer<Autofac.ContainerBuilder>(ConfigureTestContainer);
})
.CreateClient();
// Act
var request = StringContent("{\"sommat\":\"to see\"}");
request.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
var response = await client.PostAsync("/something/submit", request);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.OK);
A.CallTo(() => fakeSomethingService.DoSomething(A<string>.Ignored))
.MustHaveHappened();
}
}
}