要在ASP.NET Core集成测试中使用延迟加载代理(Lazy Loading Proxies),需要在内部使用的服务提供程序上调用AddEntityFrameworkProxies方法。以下是一个包含代码示例的解决方法:
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Proxies;
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext(options =>
options.UseLazyLoadingProxies()
.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
// 添加其他服务到容器
// ...
}
这里的ApplicationDbContext是你的数据库上下文类,将其配置为使用延迟加载代理。
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Proxies;
public class TestStartup : Startup
{
public TestStartup(IHostingEnvironment env)
: base(env)
{
}
public override void ConfigureServices(IServiceCollection services)
{
// 调用基类的ConfigureServices方法
base.ConfigureServices(services);
// 替换数据库上下文服务为测试用的内存数据库
services.AddDbContext(options =>
options.UseLazyLoadingProxies()
.UseInMemoryDatabase("TestDatabase"));
// 添加其他测试依赖的服务到容器
// ...
}
}
这里的ApplicationDbContext是你的数据库上下文类,使用内存数据库作为测试用的数据库。
public class MyIntegrationTests : IDisposable
{
private readonly TestServer _server;
private readonly HttpClient _client;
public MyIntegrationTests()
{
var builder = new WebHostBuilder()
.UseStartup();
_server = new TestServer(builder);
_client = _server.CreateClient();
}
// 测试方法
// ...
public void Dispose()
{
_client.Dispose();
_server.Dispose();
}
}
这样,你的集成测试就可以在内部使用延迟加载代理了。记得在集成测试项目中添加对Microsoft.AspNetCore.TestHost和Microsoft.EntityFrameworkCore.InMemory包的引用。