Vic*_*and 4 c# asp.net integration-testing xunit.net asp.net-core
我一直在遵循使用 ASP.NET Core 中的集成测试中的 Microsoft 文档为 ASP.NET Core 2.2 API 设置测试的策略。
总而言之,我们扩展和定制WebApplicationFactory并使用IWebHostBuilder来设置和配置各种服务,以使用内存数据库为我们提供数据库上下文以进行如下测试(从文章中复制和粘贴):
public class CustomWebApplicationFactory<TStartup>
: WebApplicationFactory<TStartup> where TStartup: class
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.ConfigureServices(services =>
{
// Create a new service provider.
var serviceProvider = new ServiceCollection()
.AddEntityFrameworkInMemoryDatabase()
.BuildServiceProvider();
// Add a database context (ApplicationDbContext) using an in-memory
// database for testing.
services.AddDbContext<ApplicationDbContext>(options =>
{
options.UseInMemoryDatabase("InMemoryDbForTesting");
options.UseInternalServiceProvider(serviceProvider);
});
// Build the service provider.
var sp = services.BuildServiceProvider();
// Create a scope to obtain a reference to the database
// context (ApplicationDbContext).
using (var scope = sp.CreateScope())
{
var scopedServices = scope.ServiceProvider;
var db = scopedServices.GetRequiredService<ApplicationDbContext>();
var logger = scopedServices
.GetRequiredService<ILogger<CustomWebApplicationFactory<TStartup>>>();
// Ensure the database is created.
db.Database.EnsureCreated();
try
{
// Seed the database with test data.
Utilities.InitializeDbForTests(db);
}
catch (Exception ex)
{
logger.LogError(ex, $"An error occurred seeding the " +
"database with test messages. Error: {ex.Message}");
}
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
在测试中,我们可以使用工厂并创建一个客户端,如下所示:
public class IndexPageTests :
IClassFixture<CustomWebApplicationFactory<RazorPagesProject.Startup>>
{
private readonly HttpClient _client;
private readonly CustomWebApplicationFactory<RazorPagesProject.Startup>
_factory;
public IndexPageTests(
CustomWebApplicationFactory<RazorPagesProject.Startup> factory)
{
_factory = factory;
_client = factory.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false
});
}
[Fact]
public async Task Test1()
{
var response = await _client.GetAsync("/api/someendpoint");
}
}
Run Code Online (Sandbox Code Playgroud)
这工作正常,但请注意在InitializeDbForTests配置服务时为所有测试设置一些测试数据的调用。
我想要一个合理的策略,用干净的石板开始每个 API 测试,这样测试就不会相互依赖。我一直在寻找各种方法来掌握ApplicationDbContext我的测试方法,但无济于事。
在彼此完全隔离的情况下进行集成测试是否合理,我该如何使用 ASP.NET Core / EF Core / xUnit.NET 来处理它?
具有讽刺意味的是,您正在寻找EnsureDeleted而不是EnsureCreated. 这将转储数据库。由于内存中的“数据库”是无模式的,因此您实际上不需要确保它被创建甚至迁移。
此外,您不应为内存数据库使用硬编码名称。这实际上会导致内存中的同一个数据库实例被到处使用。相反,您应该使用随机的东西:Guid.NewGuid().ToString()足够好。
好吧,所以我成功了!获得范围服务是关键。当我想从头开始播种时,我可以通过将播种调用包装在一个
using (var scope = _factory.Server.Host.Services.CreateScope()) { }
Run Code Online (Sandbox Code Playgroud)
我可以首先进行的部分
var scopedServices = scope.ServiceProvider;
Run Code Online (Sandbox Code Playgroud)
进而
var db = scopedServices.GetRequiredService<MyDbContext>();
Run Code Online (Sandbox Code Playgroud)
前
db.Database.EnsureDeleted()
Run Code Online (Sandbox Code Playgroud)
最后运行我的播种函数。有点笨重,但很有效。
感谢克里斯·普拉特的帮助(评论中的回答)。