【问题标题】:Dependancy Injection not working with ASPNETCore.TestHost依赖注入不适用于 ASPNETCore.TestHost
【发布时间】:2023-03-26 22:37:01
【问题描述】:

我已经为这个问题苦苦挣扎了好几个小时。我的 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   
    }

【问题讨论】:

    标签: c# asp.net-core integration-testing asp.net-core-testhost


    【解决方案1】:

    所以在两个不眠之夜之后,我发现了问题......由于一些不为人知的原因,测试服务器无法使用 apsettings.json 读取到我的数据库的连接字符串

    .AddDbContext<BoatInspectorContext>(
                    opt=>opt.UseNpgsql(Configuration.GetConnectionString("BoatInspectorConnectionString")));
    

    所以我要做的就是

    .AddDbContext<BoatInspectorContext>(
                    opt => opt.UseNpgsql(
                        connectionString:
                        "my_magic_connection_string"));
    

    由于某种原因,这个错误没有出现在任何地方,或者我没有看到它,所以在我发现它所说的内容后,它非常明显。

    【讨论】:

      猜你喜欢
      • 2012-12-31
      • 1970-01-01
      • 2017-06-16
      • 1970-01-01
      • 2019-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-07
      相关资源
      最近更新 更多