从ASP.NET Core集成测试中的WebApplicationFactory <T>获取服务

Sim*_*ane 13 asp.net-core-mvc asp.net-core asp.net-core-webapi asp.net-core-2.1

我想使用ASP.NET CoreWebApplicationFactory<T>中的Integration tests中详细说明 来设置我的测试.

在我的一些测试之前,我需要使用在真正的Startup类中配置的服务进行设置.我遇到的问题是我看不到从工厂获得服务的方法.

我可以从factory.Server使用中获取服务,factory.Host.Services.GetRequiredService<ITheType>();除非在调用factory.Server之前为null factory.CreateClient();.

我有什么方法可以使用工厂获得服务吗?

谢谢.

小智 18

您需要从服务提供商创建范围以获取必要的服务:

using (var scope = AppFactory.Server.Host.Services.CreateScope())
{
    var context = scope.ServiceProvider.GetRequiredService<MyDatabaseContext>();
}
Run Code Online (Sandbox Code Playgroud)

  • 如果factory.Server为空,请考虑首先调用factory.CreateClient()! (9认同)

Lam*_* Le 16

请原谅我。我知道您要求使用 Net Core 2.1,但自从 v3.1+ 以来,人们也来到这里......

我的项目使用 Net Core 3.1。当我使用AppFactory.Server.Host.Services.CreateScope()像 Alexey Starchikov 的建议时,我遇到了这个错误。

The TestServer constructor was not called with a IWebHostBuilder so IWebHost is not available.
Run Code Online (Sandbox Code Playgroud)

此处注明,通过设计。

所以我使用下面的方法。我将数据库播种放在测试类的构造函数中。请注意,我不必调用factory.CreateClient(). 我像往常一样在测试方法中创建客户端变量。

using (var scope = this.factory.Services.CreateScope())
{
    var dbContext = scope.ServiceProvider.GetRequiredService<YourDbContext>();

    // Seeding ...

    dbContext.SaveChanges();
}
Run Code Online (Sandbox Code Playgroud)


Ale*_*kin 8

在 APS.NET 6 和 7 中我必须使用_factory.Services.CreateScope()

using var scope = _factory.Services.CreateScope();
var sender = scope.ServiceProvider.GetRequiredService<IEmailSender>();
await sender.SendAsync("Hello");
Run Code Online (Sandbox Code Playgroud)