我已经使用.Net Core 3.0 preview 2更新了我的网站,并且我想使用 TestServer进行集成测试。在 .Net Core 2.2 中,我已经能够使用它WebApplicationFactory<Startup>
由于WebHostBuilder
即将被弃用(有关更多详细信息,请参阅(https://docs.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-2.2&tabs=visual-studio)。 ),我现在想跟进并实施新的 Generic HostBuilder
。它非常适合启动网站,但是当我启动我的集成测试时它崩溃了。我知道这WebApplicationFactory
确实有用WebHostBuilder
,这就是它崩溃的原因,但我不知道如何为 Generic 更改它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}");
}
}
});
}
}
}
我尝试使用TestServers
from Microsoft.AspNetCore.TestHost
,但它需要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