我一直在使用Integration tests in 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}");
}
}
});
}
}
在测试中我们可以使用工厂并创建一个像这样的客户端:
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来处理它?
具有讽刺意味的是,你正在寻找EnsureDeleted
而不是EnsureCreated
。这将转储数据库。由于内存中的“数据库”是无模式的,因此您实际上不需要确保创建它甚至迁移它。
此外,您不应该为内存数据库使用硬编码名称。这实际上会导致在内存中使用相同的数据库实例。相反,你应该随机使用一些东西:Guid.NewGuid().ToString()
足够好了。
实际上,Testing with InMemory在标题为“编写测试”的部分中描述了这个过程。这里有一些代码说明了基本思想
[TestClass]
public class BlogServiceTests
{
[TestMethod]
public void Add_writes_to_database()
{
var options = new DbContextOptionsBuilder<BloggingContext>()
.UseInMemoryDatabase(databaseName: "Add_writes_to_database")
.Options;
我们的想法是每个测试方法都有一个单独的数据库,因此您不必担心测试正在运行的顺序或它们并行运行的事实。当然,您必须添加一些填充数据库的代码,并从每个测试方法中调用它。
我使用过这种技术,效果很好。