我正在尝试弄清楚如何使用 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。
好吧,我认为不可能访问 SUT 的容器。老实说,我不太明白你为什么想要这样做。您将需要完全控制您的 SUT。这意味着您想要提供自己的依赖项来注入。
那,你可以!
_server = new TestServer(TestServer.CreateBuilder(null, app =>
{
app.UsePrimeCheckerMiddleware();
},
services =>
{
services.AddSingleton<IPrimeService, NegativePrimeService>();
services.AddSingleton<IPrimeCheckerOptions, PrimeCheckerOptions>();
}));
The CreateBuilder
为此提供重载。出于同样的原因,您需要提供配置和应用程序配置(原因是您希望完全控制 SUT)。我跟着this https://docs.asp.net/en/latest/testing/integration-testing.html如果您有兴趣,可以参考文章制作上面的例子。如果您愿意,我也可以将示例上传到我的 GitHub?
让我知道是否有帮助。
UpdateGitHub 示例:https://github.com/DannyvanderKraan/ASPNETCoreAndXUnit https://github.com/DannyvanderKraan/ASPNETCoreAndXUnit
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)