Xunit项目中的依赖注入 [英] Dependency injection in Xunit project
问题描述
我正在研究ASP.Net Core MVC Web应用程序.
I am working on an ASP.Net Core MVC Web application.
我的解决方案"包含2个项目:一个用于应用程序,另一个用于单元测试.
My Solution contains 2 projects: One for the application and a second project, dedicated to unit tests.
我在Tests项目中添加了对应用程序项目的引用.
I have added a reference to the application project in the Tests project.
我现在要做的是在Tests项目中编写一个类,该类将通过实体框架与数据库进行通信.
What I want to do now is to write a class in the Tests project which will communicate with the database through entity framework.
我在应用程序项目中所做的就是通过构造函数依赖项注入来访问DbContext类.
What I was doing in my application project was to access to my DbContext class through constructor dependency injection.
但是我无法在测试项目中执行此操作,因为我没有Startup.cs文件.在此文件中,我可以声明哪些服务可用.
But I cannot do this in my tests project, because I have no Startup.cs file. In this file I can declare which services will be available.
那我该怎么做才能在测试类中获得对我的DbContext实例的引用?
So what can I do to get a reference to an instance of my DbContext in the test class?
谢谢
推荐答案
您可以实现自己的服务提供商来解析DbContext
.
You can implement your own service provider to resolve DbContext
.
public class DbFixture
{
public DbFixture()
{
var serviceCollection = new ServiceCollection();
serviceCollection
.AddDbContext<SomeContext>(options => options.UseSqlServer("connection string"),
ServiceLifetime.Transient);
ServiceProvider = serviceCollection.BuildServiceProvider();
}
public ServiceProvider ServiceProvider { get; private set; }
}
public class UnitTest1:IClassFixture<DbFixture>
{
private ServiceProvider _serviceProvide;
public UnitTest1(DbFixture fixture)
{
_serviceProvide = fixture.ServiceProvider;
}
[Fact]
public void Test1()
{
using (var context = _serviceProvider.GetService<SomeContext>())
{
}
}
}
但是请记住,在单元测试中使用EF并不是一个好主意,并且最好模拟DbContext.
But bear in your mind using EF inside unit test is not good idea and it's better to mock DbContext.
The Anatomy of Good Unit Testing .
这篇关于Xunit项目中的依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!