我正在编写单元测试来测试Save DbSet的变化。代码如下:
PreSchoolContext
DbSet<Student> Students{get;set;}
PreSchoolRepository
编辑:PreSchoolContext现在是一个IPreSchoolContext实例,通过依赖注入处理。
public async Task<int> UpdatePreSchoolStudentAsync(Student student)
{
PreSchoolContext.Set<Student>().AddOrUpdate(student);
var result = await PreSchoolContext.SaveChangesAsync().ConfigureAwait(false);
return result;
}
测试方法
//Arrange
var data = GetStudents().AsQueryable();
var mockSet = new Mock<DbSet<Student>>();
mockSet.As<IQueryable<Student>>().Setup(m => m.Provider).Returns(new TestDbAsyncQueryProvider<Student>(data.Provider));
mockSet.As<IQueryable<Student>>().Setup(m => m.Expression).Returns(data.Expression);
var preSchoolContextMock = new Mock<IPreSchoolContext>();
preSchoolContextMock.Setup(c => c.Students).Returns(mockSet.Object);
var repo = new PreSchoolRepository(preSchoolContextMock.Object);
//Act
var preSchoolStudentUpdateFlag = await repo.UpdatePreSchoolStudentAsync(data.FirstOrDefault());
//Assert
preSchoolStudentUpdateFlag.ShouldNotBeNull();
preSchoolStudentUpdateFlag.ShouldBe(1);
错误
无法在派生的IDbSet类型'Castle.Proxies.DbSet`1Proxy'上调用public,实例方法AddOrUpdate。找不到方法。
无法理解正确设置模拟数据的缺失。
答案 0 :(得分:1)
我在设计中进行了一些更改以测试DbSet<>
更新功能:
在我的上下文类下添加了以下功能:
public virtual void AddOrUpdateEntity<TEntity>(IProMetrixContext db,
TEntity[] entities) where TEntity : class
{
db.Set<TEntity>().AddOrUpdate(entities);
}
然后将UpdatePreSchoolStudentAsync(Student student)
方法略微更改为:
public async Task<int> UpdateProMetrixRiskAsync(Student student)
{
PreSchoolContext.AddOrUpdateEntity<Student>(PreSchoolContext, student); //This one resolved issue of unit test and works fine in real scenario too.
var result = await PreSchoolContext.SaveChangesAsync().ConfigureAwait(false);
return result;
}
在这里引用LINK
注意:如果有人对此有任何建议,请发帖。