我已经使用.Net Core 3.0 preview 2更新了我的网站,并想要使用TestServer进行集成测试。在.Net Core 2.2中,我能够使用WebApplicationFactory<Startup>
完成它。
由于WebHostBuilder
即将被弃用(请参见(https://learn.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-2.2&tabs=visual-studio)获取更多详细信息),因此我想要跟进并实现新的通用HostBuilder
。它很适合启动网站,但是当我启动我的集成测试时会崩溃。我知道WebApplicationFactory
确实使用了WebHostBuilder
,这就是为什么会崩溃,但我不知道该如何将其更改为通用HostBuilder
。
以下是我在.Net Core 2.2中使用的代码:
namespace CompX.FunctionalTest.Web.Factory
{
public class CustomWebApplicationFactory<TStartup> : WebApplicationFactory<Startup>
{
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);
});
services.AddDbContext<AppIdentityDbContext>(options =>
{
options.UseInMemoryDatabase("Identity");
options.UseInternalServiceProvider(serviceProvider);
});
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<AppIdentityDbContext>()
.AddDefaultTokenProviders();
// 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 loggerFactory = scopedServices.GetRequiredService<ILoggerFactory>();
var logger = scopedServices.GetRequiredService<ILogger<CustomWebApplicationFactory<TStartup>>>();
// Ensure the database is created.
db.Database.EnsureCreated();
try
{
// Seed the database with test data.
var userManager = scopedServices.GetRequiredService<UserManager<ApplicationUser>>();
AppIdentityDbContextSeed.SeedAsync(userManager).GetAwaiter().GetResult();
}
catch (Exception ex)
{
logger.LogError(ex, $"An error occurred seeding the database with test messages. Error: {ex.Message}");
}
}
});
}
}
}
我尝试使用来自 Microsoft.AspNetCore.TestHost 的 TestServers,但它需要 new WebHostBuilder() 作为参数。
我还尝试将其作为参数传递,但也没有成功:
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
它找不到.ConfigureWebHostDefaults()
函数。
有人在.NET Core 3.0中成功实现了测试服务器吗? 非常感谢!
PS:我对.NET Core有点陌生。
编辑:
这是 program.cs
:
namespace CompX.Web
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
这是我在 Github 上创建的问题: https://github.com/aspnet/AspNetCore/issues/7754