【问题标题】:Unresolved constructor arguments error when trying to use dependency injection with XUnit尝试对 XUnit 使用依赖注入时出现未解决的构造函数参数错误
【发布时间】:2018-09-27 20:27:15
【问题描述】:

我的每个 XUnit 测试项目都有一个 appsettings.json 文件,其中指定了一些设置。我一直使用 IConfiguration 依赖注入来检索我的测试夹具类中的这些设置。现在我想起来了,我完全不知道过去 IConfiguration 是如何解决的,因为 XUnit 项目中没有 Startup.cs 和 ConfigureServices 方法。但我发誓它有效。

以前可以用,现在不行了:

夹具:

public class TestFixture : IDisposable
{
    public IConfiguration Configuration { get; set; }

    public TestFixture(IConfiguration configuration)
    {
        Configuration = configuration;
    }
}

测试类:

public class TestCases : IClassFixture<TestFixture>
{
    public TestCases(TestFixture fixture)
    {

    }
}

我收到的错误如下:

消息:System.AggregateException:发生一个或多个错误。 ---- 类夹具类型“MyProj.Tests.TestFixture”有一个或多个未解析的构造函数参数:IConfiguration 配置 ---- 以下构造函数参数没有匹配的夹具数据:TestFixture 夹具

【问题讨论】:

  • 这在技术上显然是可行的,但极不可能; xUnit 的人已经做了很多声明,大意是没有计划或希望在这里和 Github 问题上进行一般 DI
  • @RubenBartelink 你认为这很奇怪吗,它在过去以某种方式工作,而现在由于最新版本的 XUnit 或 .NET Core 2.0 而不能工作?
  • 肯定有一些奇怪的东西,但我想不出任何理由相信 xUnit 在某个时间点创建了由明确的IClassFixture 和/或CollectionAttribute 指定的东西以外的东西用法。唯一突然出现在我脑海中的是一个默认构造函数,它隐藏了依赖项和/或测试类是私有的等,但假设某些东西对你有用,所以它一定是别的东西
  • 试试 xunit 框架中内置的 xunit di 支持:nuget.org/packages/Xunit.Di,这样您就可以像对任何其他应用程序一样注入服务依赖项。

标签: c# asp.net-core xunit xunit.net


【解决方案1】:

我想知道为什么我有像你这样的代码,因为文档 (https://xunit.github.io/docs/shared-context) 没有说明在夹具中使用 DI...在我的情况下,我通过删除 DI 解决了它,因为我遇到了与你相同的错误.

然后我有这样一个代码来拥有一个用于单元测试的服务集合。

var services = new ServiceCollection();
ConfigureServices(services);
IServiceProvider serviceProvider = services.BuildServiceProvider();

// Assign shortcuts accessors to registered components
UserManager = serviceProvider.GetRequiredService<UserManager<User>>();
RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole<string>>>();

My ConfigureServices() 在将服务注册到集合之前调用此代码,因此这回答了您关于 IConfiguration 的问题。请注意,我现在使用 .net core 2.1,之前使用的是 2.0。 但我还是和你和其他评论的人一样想知道,为什么 DI 之前没有崩溃?

private static IConfiguration LoadConfiguration()
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json");

        return builder.Build();
    }

【讨论】:

【解决方案2】:



我知道这个问题已经很老了,但也许该解决方案对某些人有用。

我遇到了同样的问题,并通过使用 WebApplicationFactory 泛型类修复了它。希望这将是其他人的解决方案。

替换

: IClassFixture<TestFixture> ->
: IClassFixture<WebApplicationFactory<Startup>>

更多详情,您可以访问the official page

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-04
    • 2015-05-12
    相关资源
    最近更新 更多