依赖注入具有的xUnit和ASP.NET 1.0的核心 [英] Dependency Injection with XUnit and ASP.NET Core 1.0

查看:868
本文介绍了依赖注入具有的xUnit和ASP.NET 1.0的核心的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出我如何使用依赖注入的xUnit。我的目标是能够注入我ProductRepository到我的测试类。

I am trying to figure out how I can use dependency injection with XUnit. My goal is to be able to inject my ProductRepository into my test class.

下面是code我想:

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库)

Here is the error: The following constructor parameters did not have matching fixture data (ICustomerRepository repository)

这使我相信的xUnit好好尝试一下支持依赖注入,只有当它是一个夹具。

This leads me to believe that XUnit doens't support dependency injection, only if it is a Fixture.

有人可以给我用的xUnit越来越ProductRepository的一个实例,在我的测试类的方法吗?我相信我正常启动了一个测试服务器,因此Startup.cs运行,并配置DI。

Can someone give me a way of getting an instance of ProductRepository in my test class using XUnit? I believe I am correctly starting up a test server so Startup.cs runs and configures the DI.

推荐答案

好吧,我不认为这是可能访问SUT的容器。而且说实话我不完全明白你为什么会想。你会希望你的SUT的完全控制。这意味着你要提供你自己的依赖注入。

Well, I don't think it is possible to access the container of the SUT. And to be honest I don't exactly understand why you'd want to. You will want complete control of your SUT. That means you want to provide your own dependencies to inject.

而这,你可以!

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

CreateBuilder 提供重载这一点。你需要为同样的原因,配置和应用配置(之所以被你想在你的SUT完全控制)。我跟着文章,使上面的例子,如果你有兴趣。如果你想我也可以上传样品到我的GitHub?

The CreateBuilder provides overloads for this. You'll need to provide configurations and app configurations for the same reasons (reason being you want complete control over your SUT). I followed this article to make the above example if you are interested. I could also upload the sample to my GitHub if you want?

让我知道,如果它帮助。

Let me know if it helped.

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

这篇关于依赖注入具有的xUnit和ASP.NET 1.0的核心的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆