【问题标题】:Dependency Injection with XUnit and ASP.NET Core 1.0使用 XUnit 和 ASP.NET Core 1.0 进行依赖注入
【发布时间】:2016-06-26 01:08:07
【问题描述】:

我试图弄清楚如何在 XUnit 中使用依赖注入。我的目标是能够将我的 ProductRepository 注入到我的测试类中。

这是我正在尝试的代码:

public class DatabaseFixture : IDisposable
{
    private readonly TestServer _server;

    public DatabaseFixture()
    {
        _server = new TestServer(TestServer.CreateBuilder().UseStartup<Startup>());
    }

    public void Dispose()
    {
        // ... clean up test data from the database ...
    }
}

public class MyTests : IClassFixture<DatabaseFixture>
{
    DatabaseFixture _fixture;
    public ICustomerRepository _repository { get; set; }

    public MyTests(DatabaseFixture fixture, ICustomerRepository repository)
    {
        _fixture = fixture;
        _repository = repository;
    }
}

这是错误: 以下构造函数参数没有匹配的夹具数据(ICustomerRepository 存储库)

这让我相信 XUnit 不支持依赖注入,除非它是一个 Fixture。

有人可以给我一种使用 XUnit 在我的测试类中获取 ProductRepository 实例的方法吗?我相信我正确地启动了一个测试服务器,因此 Startup.cs 运行并配置了 DI。

【问题讨论】:

  • 试试 xunit 框架中内置的 xunit di 支持:nuget.org/packages/Xunit.Di,这样您就可以像对任何其他应用程序一样注入服务依赖项。

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


【解决方案1】:

好吧,我认为无法访问 SUT 的容器。老实说,我不完全明白你为什么想要。您将需要完全控制您的 SUT。这意味着您想提供自己的依赖项来注入。

而且,你可以!

_server = new TestServer(TestServer.CreateBuilder(null, app =>
{
    app.UsePrimeCheckerMiddleware();
},
services =>
{
    services.AddSingleton<IPrimeService, NegativePrimeService>();
    services.AddSingleton<IPrimeCheckerOptions, PrimeCheckerOptions>();
}));

CreateBuilder 为此提供了重载。出于同样的原因,您需要提供配置和应用程序配置(原因是您希望完全控制您的 SUT)。如果您有兴趣,我按照this 的文章制作了上述示例。如果你愿意,我也可以将示例上传到我的 GitHub?

如果有帮助,请告诉我。

更新 GitHub示例:https://github.com/DannyvanderKraan/ASPNETCoreAndXUnit

【讨论】:

  • Danny 如果你能上传一个例子到 github 那就太棒了。我不得不承认我还是有点困惑。假设我有一个 IProductRepo 和一个 ProductRepo:你能给我举个例子,说明使用 DI 获取 ProductRepo 实例的正确方法,以便我可以在我的测试类中使用它吗?
  • 布莱克,我已经更新了我的答案。您要做的是,您将编写 IProductRepo 而不是 IPrimeService,而不是 NegativePrimeService,您将编写 ProductRepo。希望现在清楚。
  • 嗨@DannyvanderKraan 你能回答这个问题吗?谢谢 ! stackoverflow.com/questions/57331395/…
猜你喜欢
  • 2016-06-25
  • 1970-01-01
  • 2020-06-30
  • 2016-09-27
  • 2020-06-30
  • 2010-12-07
  • 1970-01-01
  • 2017-06-09
  • 2015-04-05
相关资源
最近更新 更多