如何在集成测试中访问内存数据库的dbcontext?
并具有与以下类似的测试:
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
});
}
在此IndexPageTests中是否可以访问内存中的dbcontext?
我尝试过
using (var context = new ApplicationDbContext(???))
我需要访问我以前从CustomWebApplicationFactory播种的表中的数据
但不确定要放置什么选项
答案 0 :(得分:2)
感谢Nikosi,这是我设法获得dbcontext的方法
var scopeFactory = _factory.Server.Host.Services.GetService<IServiceScopeFactory>();
using (var scope = scopeFactory.CreateScope())
{
var context = scope.ServiceProvider.GetService<ApplicationDbContext>();
}