使用XUnit和ASP.NET Core 1.0进行依赖注入

Bla*_*ell 8 c# asp.net xunit asp.net-core asp.net-core-1.0

我试图找出如何使用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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

这让我相信XUnit不支持依赖注入,只有它是一个Fixture.

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

Dan*_*aan 7

好吧,我认为不可能访问SUT的容器.说实话,我并不完全理解你为什么这么想.您需要完全控制您的SUT.这意味着你想提供自己的依赖注入.

而那,你可以!

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

CreateBuilder此提供过载.出于同样的原因,您需要提供配置和应用程序配置(原因是您希望完全控制SUT).如果您有兴趣,我会按照这篇文章制作上面的例子.如果你愿意,我也可以将样本上传到我的GitHub?

如果有帮助,请告诉我.

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