Moq为Generic Repository生成测试

时间:2014-05-13 16:45:30

标签: c# moq

如何使用MOQ来模拟使用Generic Repository的以下方法?

public Employee GetEmployeeByUserName(Employee employee)
{
   return _employeeRepository.Find().FirstOrDefault(i => i.User_Name == 
          employee.User_Name);
}

我用这个来解决moq问题:

mockEmployeeRep.Setup(rep=>rep.Find()......<------What goes here?

这利用了以下存储库:

public class EmployeeRepository<T> : IRepository<T> where T : class        
{           
        ... 
        public IQueryable<T> Find()    
        {    
            var table = this.LookupTableFor(typeof(T));    
            return table.Cast<T>();    
        }   
        ...
}

1 个答案:

答案 0 :(得分:3)

moq IQueryable的最简单方法是使用List<T>并使用AsQueryable方法。

var employees = new List<Employee>();

employees.Add(...);

var mockEmployeeRepository = new Mock<IRepository<Employee>>();

mockEmployeeRepository.Setup(x => x.Find()).Returns(employees.AsQueryable());

// continue with the rest of your test setup