作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我为我的核心 1.0 应用程序添加了一个测试项目。在其中我有在构造函数中使用 dbContext 的存储库。
如何在测试项目中访问此 dbContext 并正确注入(inject)?
这是我的 ApplicationDbContext 类:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
}
public DbSet<Category> Categories { get; set; }
public DbSet<Product> Products { get; set; }
public DbSet<ShoppingCartItem> ShoppingCartItems { get; set; }
public DbSet<Order> Orders { get; set; }
public DbSet<OrderDetail> OrderDetails { get; set; }
}
[Fact]
public void ProductsGetAll()
{
//here i need to get acces to dbContext and inject it below
ProductRepository productRepository = new ProductRepository(dbContext);
CategoryRepository categoryRepository = new CategoryRepository(dbContext);
ProductController productController = new ProductController(productRepository, categoryRepository);
}
ApplicationDbContext dbContext;
public UnitTest1()
{
var options = new DbContextOptionsBuilder<ApplicationDbContext>()
.UseInMemoryDatabase(databaseName: "FakeDatabase")
.Options;
dbContext = new ApplicationDbContext(options);
}
[Fact]
public void ProductsGetAll()
{
IProductRepository productRepository = new ProductRepository(dbContext);
ICategoryRepository categoryRepository = new CategoryRepository(dbContext);
ProductController productController = new ProductController(productRepository, categoryRepository);
var result = productController.List("Pizza");
var contentResult = result as ViewResult;
var final = contentResult != null;
Assert.False(final, "Shouldnt be null");
Message: System.NullReferenceException : Object reference not set to an instance of an object.
最佳答案
我创建了一个 interface , 并将所有 DbSets 放入其中。
public class ApplicationDbContext :
IdentityDbContext<ApplicationUser>, IDbContext
{
...
public DbSet<Category> Categories { get; set; }
...
}
public interface IDbContext
{
DbSet<Category> Categories { get; set; }
...
}
public class UserRepository : IUserRepository
{
private readonly IDbContext _context;
public UserRepository(IDbContext context)
{
_context = context;
}
}
var mockSet = MockHelper.GetMockDbSet(_users);
var mockDbContext = new Mock<IDbContext>();
mockDbContext.Setup(x => x.Users).Returns(mockSet.Object);
varmockDbContext = mockDbContext.Object;
IProductRepository
而不是
ProductRepository
.
var mockProductRepository = new Mock<IProductRepository>();
mockProductRepository.Setup(x => x.GetAllProductsAsync()).ReturnsAsync(_products);
var productController = new ProductController(mockProductRepository.Object,...);
关于c# - 如何在 xUnit 测试项目中使用 DbContext?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49449971/
我是一名优秀的程序员,十分优秀!