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:
- 一个用于应用程序和
- 第二个项目,专门用于单元测试 (XUnit).
我在 Tests 项目中添加了对应用项目的引用.
I have added a reference to the application project in the Tests project.
我现在想做的是在XUnit Tests项目中写一个类,通过实体框架与数据库进行通信.
What I want to do now is to write a class in the XUnit 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 _serviceProvider;
public UnitTest1(DbFixture fixture)
{
_serviceProvider = fixture.ServiceProvider;
}
[Fact]
public void Test1()
{
using (var context = _serviceProvider.GetService<SomeContext>())
{
}
}
}
但请记住,在单元测试中使用 EF 不是一个好主意,最好模拟 DbContext.
But bear in your mind using EF inside a unit test is not a good idea and it's better to mock DbContext.
这篇关于Xunit 项目中的依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!