代码之家  ›  专栏  ›  技术社区  ›  Bob5421

Xunit项目中的依赖注入

  •  7
  • Bob5421  · 技术社区  · 7 年前

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

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

    那么,如何才能在测试类中获取对dbContext实例的引用呢?

    3 回复  |  直到 6 年前
        1
  •  5
  •   Mohsen Esmailpour    6 年前

    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>())
            {
            }
        }
    }
    

    The Anatomy of Good Unit Testing

        2
  •  1
  •   Paul Adam    6 年前

    public ClassName : IDisposable
    {
        private SomeClassRepository _repository;
        private Mock<DbSet<SomeClass>> _mockSomeClass;
    
        public ClassName() 
        {
            _mockSomeClass = new Mock<DbSet<SomeClass>>();
    
            var mockContext = new Mock<IApplicationDbContext>();
            mockContext.SetupGet(c => c.SomeClass).Returns(_mockSomeClass.Object);
    
            _repository = new SomeClassRepository(mockContext.Object);
        }
    
        public void Dispose()
        {
            // Anything you need to dispose
        }
    
        [Fact]
        public void SomeClassTest()
        {
            var someClass = new SomeClass() { // Initilize object };
    
            _mockSomeClass.SetSource(new[] { someClass });
    
            var result = _repository.GetSomethingFromRepo( ... );
    
            // Assert the result
        }
    }
    

    对于集成测试,您执行相同的操作,但设置是:

    _context = new ApplicationDbContext();
    

    TestClass 继承自 IDisposable TestClass : IDisposable )以便在每次测试后释放上下文。

    https://xunit.github.io/docs/shared-context

        3
  •  0
  •   A. Wheatman    6 年前