【文章推荐】ASP.NET Core Functional Test
Closed this issue · 1 comments
gaufung commented
不同于单元测试,功能测试(或者集成测试)是一种端到端的测试,它会尽可能的测试软件或者系统对外界暴露的接口测试,而且外部依赖保持一致。在 ASP.NET Core
中,我们对外暴露的是 Web API 请求,依赖可能是数据库,文件系统访问等等。我们可以借助两个库完成上述的的要求
- Microsoft.AspNetCore.Mvc.Testing
该库的作用是拷贝应用程序的依赖至测试功能,并且内容根目录内容至测试工程下,并且提供了 WebApplicationFactory
来启动测试服务。
public class IntegrationTestWebApplicationFactory : WebApplicationFactory<Program>
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.ConfigureTestServices(services =>
{
services.RemoveAll(typeof(DbContextOptions<ApplicationDbContext>));
// Add Integration test Dbcontext
});
builder.UseEnvironment("Development");
}
}
- TestContainer
这个库帮助我们运行一个 Container,然后将我们的外部依赖,比如数据库给运行起来,这样就能在测试的时候直接连接该数据库。
PostgreSqlContainer _dbContainer = new PostgreSqlBuilder()
.WithImage("Postgres:latest")
.WithDatatabase("runtrack")
.WithUserName("User")
.WithPassword("password")
.Build()
这样就能获得一个 Postgre
数据库,在我们 WebApplicationFactory
构造 WebHost
的时候,将它作为数据库的来源。