我在这个问题上一直在挣扎很多小时。我的WebAPI应用程序在本地机器和生产服务器上正常工作,但在具有依赖注入的控制器的集成测试中失败。一切看起来都很干净,我不知道为什么这不起作用。
因此,模块来了:控制器:
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);
}
如果我进行调试,调试器甚至都不会进入控制器构造函数。如果我评论构造函数并创建一个空的构造函数,一切都可以正常工作,所以这与依赖注入有关100%。请帮忙。谢谢。
更新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"));
由于某种原因,此错误并没有出现在任何地方,或者也许我没有看到它,所以在我发现它说的很明显之后。