【问题标题】:Cannot use constructor parameters with dependency injection in asp.net core test无法在 asp.net 核心测试中使用带有依赖注入的构造函数参数
【发布时间】:2021-10-16 10:13:39
【问题描述】:

我使用WebHostBuilder 类来配置服务器以在asp.net 核心中进行集成测试。虽然这很有魅力,但我现在遇到了具有构造函数参数以及其他依赖项的服务的问题。这些服务在我的启动中注册,模式如下:

        services.AddSingleton<MyInterface, MyClass>(x =>
            new MyClass(x.GetRequiredService<SomeInterfaceDependency>(),
                        x.GetRequiredService<AnotherInterfaceDependency>(),
                        someStringOrEnumOrWhateverParameter));

当我运行测试时,我使用此服务的请求失败了,我什至不明白请求在什么时候失败。我得到的诊断信息仅限于一行堆栈跟踪:

    ThreadOperations.ExecuteWithAbortSafety(Action action)

所以我的问题是:如何在集成测试中使用具有构造函数参数的服务?非常感谢任何正确方向的指针。谢谢。

【问题讨论】:

    标签: asp.net-core dependency-injection integration-testing


    【解决方案1】:

    您不应该手动创建WebHostBuilders,而是使用Microsoft.AspNetCore.Mvc.Testing 包及其TestServerWebApplicationFactory 类为您完成这一切,如MSDN 中所述:

    https://docs.microsoft.com/aspnet/core/test/integration-tests?view=aspnetcore-5.0#aspnet-core-integration-tests

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-07
      • 2019-10-30
      • 2019-03-29
      • 2015-05-12
      • 2019-02-16
      • 2016-10-10
      • 1970-01-01
      相关资源
      最近更新 更多