C# 使用Moq进行单元测试,并使用include设置GetAll

C# 使用Moq进行单元测试,并使用include设置GetAll,c#,nunit,moq,vs-unit-testing-framework,C#,Nunit,Moq,Vs Unit Testing Framework,我的MOQ有一个奇怪的问题,我不能使用GetAll('include')方法来测试我的控制器 我的测试初始化 // GetAll menusDb.Setup(m => m.GetAll()).Returns(menus.AsQueryable()); menusDb.Setup(m => m.GetAll(It.IsAny<Expression<Func<Menu, object>>>())) .Returns((Expression

我的MOQ有一个奇怪的问题,我不能使用GetAll('include')方法来测试我的控制器

我的测试初始化

// GetAll
menusDb.Setup(m => m.GetAll()).Returns(menus.AsQueryable());
menusDb.Setup(m => m.GetAll(It.IsAny<Expression<Func<Menu, object>>>()))
       .Returns((Expression<Func<Menu,object>> pred) => { 
           return menus.AsQueryable();
       });
// FindByIdAsync
menusDb.Setup(m => m.FindByByIdAsync(It.IsAny<int>()))
       .Returns((int x) => Task.FromResult(menus.Find(m => m.ID == x)));
menusDb.Setup(m => m.FindByByIdAsync(It.IsAny<int>(), It.IsAny<Expression<Func<Menu, object>>[]>()))
       .Returns((int x, Expression<Func<Menu,
           object>>[] includeProperties) => Task.FromResult(menus.Find(m => m.ID == x)));
MenuDB.getAll()方法的moq版本根本没有被激发

所有其他Moq方法均已正确触发。。。 例子

_menusDB.GetAll();
_menusDB.FindByByIdAsync(id,
                m => m.Sections.Select(s => s.Image),
                m => m.Sections.Select(s => s.MenuItems.Select(mi => mi.Image)));
这些是我的通用存储库中包含的Getall和find函数

public IQueryable<TEntity> GetAll<TProperty>(Expression<Func<TEntity, TProperty>> propertyToInclude) {            
    return ObjectSet.Include(propertyToInclude);
}

public async Task<TEntity> FindByByIdAsync(int id, params Expression<Func<TEntity, object>>[] propertiesToInclude) {            
    var query = propertiesToInclude.Aggregate(ObjectSet as IQueryable<TEntity>, (current, property) => current.Include(property));
    return await query.SingleOrDefaultAsync(entity => entity.ID == id).ConfigureAwait(false);
}
public IQueryable GetAll(表达式属性包括){
返回ObjectSet.Include(propertyToInclude);
}
公共异步任务FindByByIdAsync(int-id,参数表达式[]propertiesToInclude){
var query=propertiesToInclude.Aggregate(ObjectSet为IQueryable,(当前,属性)=>current.Include(属性));
返回wait query.SingleOrDefaultAsync(entity=>entity.ID==ID).configureWait(false);
}

我终于找到了问题所在。GetAll with include使用泛型TProperty而不是object来包含属性。Mock无法以某种方式将对象Tproperty与我在测试中提供的linq查询联系起来。也许有办法让它工作,但现在我只是将泛型属性改为object

public IQueryable<TEntity> GetAll<TProperty>(Expression<Func<TEntity, TProperty>> propertyToInclude) {            
    return ObjectSet.Include(propertyToInclude);
}

public async Task<TEntity> FindByByIdAsync(int id, params Expression<Func<TEntity, object>>[] propertiesToInclude) {            
    var query = propertiesToInclude.Aggregate(ObjectSet as IQueryable<TEntity>, (current, property) => current.Include(property));
    return await query.SingleOrDefaultAsync(entity => entity.ID == id).ConfigureAwait(false);
}