进行单元测试时,在dbset中添加新实体后,我无法从dbset收集收集,它会抛出一个异常'收集'<</strong>/p>
这是我的代码设置
[TestMethod]
[TestCategory("Skill Category")]
public void Create_Skill_Category()
{
var category = new SkillCategoryModel() { CategoryId = 3, CategoryName = "Category 3" };
var result = skillManager.SaveSkillCategory(category);
Assert.IsNotNull(result, "Category can't be null");
Assert.AreEqual(category.CategoryId, result.CategoryId, "Category id must be equal");
var categoryList = skillManager.GetCategories(); // here exception thrown
Assert.IsTrue(categoryList.Count == 3, "Categories List must be contain three category");
}
private ISkill skillManager;
[TestInitialize]
public void Init()
{
var category = new SkillCategory { CategoryId = 1, CategoryName = "Category 1" };
var categories = new List<SkillCategory>
{
category,
new SkillCategory { CategoryId = 2, CategoryName = "Category 2" }
};
var categoryMockSet = Utility.GenerateMockEntity(categories);
categoryMockSet.Setup(x => x.Add(It.IsAny<SkillCategory>())).Callback<SkillCategory>(x => categories.Add(x)).Returns<SkillCategory>(x => x);
var mock = new Mock<WhoEntities>();
mock.Setup(q => q.SkillCategories).Returns(categoryMockSet.Object);
mock.CallBase = true;
skillManager = new WhoGroup.DML.Managers.SkillManager(mock.Object);
}
在这里,我无法理解我在这种情况下做错了什么。作为参考,我正在使用此链接:
实体框架6和MOQ4:是否有可能在其范围内保留模拟的DBSET保留数据?
以下语句不正确:
entityMockSet.As<IEnumerable<TEntity>>()
.Setup(m => m.GetEnumerator()).Returns(query.GetEnumerator());
每个请求都会返回相同的 Enumerator
,这导致您只能使用枚举器曾经>
哪些部分解决问题是每次调用GetEnumerator
时要重置枚举器,因为您可以仅使用Add
-Method
解决方案:真正解决的问题是在设置getEnumerator方法时使用lambda:
entityMockSet.As<IEnumerable<TEntity>>()
.Setup(m => m.GetEnumerator()).Returns(() => query.GetEnumerator());
这部分非常重要: .Returns(
()=> query.GetEnumerator());
因为使用此请求时,有一个新的枚举者会返回。
该错误发生在MOQ DBSET中,因为在DB集中添加新实体后,我没有更新GetEnumerer的引用。
public class Utility
{
public static Mock<DbSet<TEntity>> GenerateMockEntity<TEntity>(List<TEntity> entityList) where TEntity : class
{
var list = new List<TEntity>();
list.AddRange(entityList);
var query = list.AsQueryable();
var entityMockSet = new Mock<DbSet<TEntity>>() { CallBase = true};
entityMockSet.As<IQueryable<TEntity>>().Setup(m => m.Provider).Returns(query.Provider);
entityMockSet.As<IQueryable<TEntity>>().Setup(m => m.Expression).Returns(query.Expression);
entityMockSet.As<IQueryable<TEntity>>().Setup(m => m.ElementType).Returns(query.ElementType);
entityMockSet.As<IEnumerable<TEntity>>().Setup(m => m.GetEnumerator()).Returns(query.GetEnumerator());
entityMockSet.Setup(x => x.Add(It.IsAny<TEntity>())).Callback<TEntity>(x => {
list.Add(x);
entityMockSet.As<IEnumerable<TEntity>>().Setup(m => m.GetEnumerator()).Returns(list.GetEnumerator());
}).Returns<TEntity>(x => x);
return entityMockSet;
}
}