【发布时间】:2019-09-12 15:14:18
【问题描述】:
我一直在遵循使用 Microsoft 文档 Integration tests in ASP.NET Core 为 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}");
}
}
});
}
}
在测试中我们可以使用工厂并像这样创建一个客户端:
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");
}
}
这很好用,但请注意对InitializeDbForTests 的调用,它会在配置服务时为所有测试设置一些测试数据。
我想要一个合理的策略,让每个 API 测试都从头开始,这样测试就不会相互依赖。我一直在寻找各种方法来在我的测试方法中获取ApplicationDbContext,但无济于事。
在彼此完全隔离的情况下进行集成测试是否合理,我如何使用 ASP.NET Core / EF Core / xUnit.NET 来处理它?
【问题讨论】:
标签: c# asp.net asp.net-core integration-testing xunit.net