我已经为这个问题苦苦挣扎了好几个小时。我的 WebAPI 应用程序在本地机器和生产服务器上运行良好,但在具有依赖注入(inject)的 Controller 的集成测试期间失败。一切看起来都很干净,我不知道为什么这不起作用。
所以这里有模块: Controller :
public SurveyController(IBoatInspectorRepository<Survey> repository)
{
_repository = repository;
}
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] {"value1", "value2"};
}
启动:
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IBoatInspectorRepository<Survey>, BoatInspectorRepository<Survey>>();
}
测试:
[Test]
public async Task GetSurveyDb_NullReturn_ReturnNotFound()
{
using (var testServer = CreateTestServer())
{
var client = testServer.CreateClient();
var value = await client.GetAsync("/api/survey/");
}
}
private TestServer CreateTestServer()
{
var builder = new WebHostBuilder()
.UseStartup<Startup>()
.ConfigureServices(services =>
services.AddScoped<IBoatInspectorRepository<Survey>, BoatInspectorRepository<Survey>>());
return new TestServer(builder);
}
如果我对此进行调试,调试器甚至不会进入 Controller 构造函数。如果我注释掉构造函数并创建一个空的构造函数,一切正常,所以它 100% 与依赖注入(inject)有关。请帮忙。谢谢。
更新 1
所以这似乎是上下文初始化的问题,因为如果我执行以下操作,构造函数也不会初始化。
public SurveyController(BoatInspectorContext context)
{
//debuger doesn't go inside here so must be something with context
}
最佳答案
所以在两个不眠之夜之后,我发现了错误......由于一些不常见的原因,测试服务器无法使用 apsettings.json 读取连接字符串到我的数据库
.AddDbContext<BoatInspectorContext>(
opt=>opt.UseNpgsql(Configuration.GetConnectionString("BoatInspectorConnectionString")));
所以我所要做的就是
.AddDbContext<BoatInspectorContext>(
opt => opt.UseNpgsql(
connectionString:
"my_magic_connection_string"));
由于某种原因,这个错误并没有出现在任何地方,或者也许我没有看到它,所以在我发现它所说的内容后,它就非常明显了。
关于c# - 依赖注入(inject)不适用于 ASPNETCore.TestHost,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47818196/