Xunit项目中的依赖注入

Bob*_*421 9 dependency-injection xunit asp.net-core-mvc

我正在研究ASP.Net Core MVC Web应用程序。

我的解决方案包含2个项目:一个用于应用程序,另一个用于单元测试。

我在“测试”项目中添加了对应用程序项目的引用。

我现在要做的是在Tests项目中编写一个类,该类将通过实体框架与数据库进行通信。

我在应用程序项目中所做的工作是通过构造函数依赖项注入来访问DbContext类。

但是我无法在测试项目中执行此操作,因为我没有Startup.cs文件。在此文件中,我可以声明哪些服务可用。

那么,如何在测试类中获取对DbContext实例的引用?

谢谢

Moh*_*our 8

您可以实施自己的服务提供商来解决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>())
        {
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是请记住,在单元测试中使用EF并不是一个好主意,并且模拟DbContext更好。

好的单元测试的剖析


Mr.*_*kin 5

您可以使用Xunit.DependencyInjection

  • 扩展它的作用以及为什么它比其他方法更好在这里将非常有用。还添加一个小示例演示它在使用时的外观会很棒。 (25认同)