unittest moq dbContext, entityframeworkCore
写个 helper
public class MoqDbContext
{
private Mock<DataContext> contextMock;
public MoqDbContext()
{
DbContextOptions<DataContext> options = new DbContextOptions<DataContext>();
contextMock = new Mock<DataContext>(options);
}
public MoqDbContext AddDBContext<T>(Expression<Func<DataContext, DbSet<T>>> expression, List<T> data) where T : class
{
contextMock.Setup(expression).ReturnsDbSet(data);
return this;
}
public DataContext Create()
{
return contextMock.Object;
}
}
使用的时候
//Act
var _context = new MoqDbContext()
.AddDBContext(x => x.TranslationMemory, translationMemories)
//.AddDBContext(x => x.Resource, resoureData) //Adding multiple Entities
.Create();