在从.NET Core 2迁移到3的过程中,我注意到WebApplicationFactory
发生了重大变化。复制:https://github.com/lukasz-pyrzyk/orderofconfigureservices
在用于集成测试的基础库中,我使用WebApplicationFactory
来设置服务器和配置服务。例如,假设以下服务
public interface IHelloService
{
string Say();
}
public class HelloService : IHelloService
{
public string Say() => "Hello from original service";
}
public class CustomHelloService : IHelloService
{
public string Say() => "Hello from custom service";
}
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.TryAddSingleton<IHelloService, HelloService>();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
}
}
集成测试的基类,灯具看起来如下
public class TestFixture : IntegrationTests<Startup>
{
[Fact]
public void SayHallo()
{
var service = Services.GetService<IHelloService>();
Assert.Equal("Hello from custom service", service.Say());
}
protected override void ConfigureServices(IServiceCollection services)
{
services.TryAddSingleton<IHelloService, CustomHelloService>();
}
}
public abstract class IntegrationTests<TStartup> : IDisposable where TStartup : class
{
private readonly WebApplicationFactory<TStartup> _factory;
protected IntegrationTests() : this(typeof(TStartup).Assembly.GetName().Name)
{
}
protected IntegrationTests(string projectRelativePath)
{
_factory = new WebApplicationFactory<TStartup>().WithWebHostBuilder(b =>
{
b
.UseSolutionRelativeContentRoot(Path.Combine("src", projectRelativePath))
.ConfigureServices(ConfigureServices);
});
_factory.CreateClient();
Services = _factory.Services;
}
protected IServiceProvider Services { get; }
protected virtual void ConfigureServices(IServiceCollection services)
{
}
public void Dispose()
{
_factory.Dispose();
}
}
在.NET Core 2.1
和Microsoft.AspNetCore.Mvc.Testing 2.1.3
上的方法TestFixture.ConfigureServices()
被称为之前 Startup.ConfigureServices
和测试通过。
在.NET Core 3.1
和Microsoft.AspNetCore.Mvc.Testing 3.1.1
上,方法TestFixture.ConfigureServices()
被称为之后 Startup.ConfigureServices
和测试失败。
您知道此更改是否是有意的吗?使用.NET Core 2.1,首先调用来自test的ConfigureServices,并且TryAddSingleton
正在注册我的模拟服务。稍后,Startup.ConfigureServices
跳过了注册,因为已经添加了服务。
使用.NET Core 3.1,我不得不调用AddSingleton
来替换服务。是错误还是想要的更改?我可以以某种方式克服它吗?
仅对于其他人,它是由设计更改的。