为什么这个测试在moq下失败了

时间:2014-04-24 13:33:49

标签: unit-testing moq

使用MOQ和通用存储库。我无法成功测试以下方法。

[TestMethod()]
    public void Employee_Service_Get_Users()
    {

        var mockRep = new Mock<IRepository<Employee>>(MockBehavior.Strict);

        IList<Employee> newEmpLst = new List<Employee>();
        Employee newEmp = new Employee();            

        mockRep.Setup(repos => repos.Find()   <------ What belongs here?

        var service = new EmployeeService(mockRep.Object);
        var createResult = service.GetAllActiveEmployees();

        Assert.AreEqual(newEmpLst, createResult);

    }

它正在调用此方法:

public IList<Employee> GetAllActiveEmployees()
    {
        return _employeeRepository.Find()
               .Where(i=>(i.Status =="Active")).ToList();  <----It Bombs Here! ;)
    }

My Generic Repository具有以下内容:

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

我得到以下内容:

Moq.MockException: IRepository`1.Find() invocation failed with 
mock  behavior Strict. All invocations on the mock must have a corresponding 
setup.

2 个答案:

答案 0 :(得分:3)

您尚未提供IRepository<T> Find()的完整方法签名,但猜测时,它类似于IQueryable<T> Find()。因为我们想要模拟它来返回少量假数据,所以我们只是将它绑定到内存列表中并不重要。由于SUT会执行过滤器(Active),因此请确保您还在假数据中提供不需要的数据,以确保SUT的过滤逻辑正常运行。

假设所有这些,您的设置将如下所示:

 var newEmpLst = new List<Employee>
 {
    new Employee()
    {
        Name = "Jones",
        Status = "Active"
    },
    new Employee()
    {
        Name = "Smith",
        Status = "Inactive"
    },
 };

mockRep.Setup(repos => repos.Find())
       .Returns(newEmpLst.AsQueryable());

你的行为+断言就像是:

var service = new EmployeeService(mockRep.Object);
var createResult = service.GetAllActiveEmployees();

Assert.AreEqual(1, createResult);
Assert.IsTrue(createResult.Any(x => x.Name == "Jones"));
Assert.IsFalse(createResult.Any(x => x.Name == "Smith"));

mockRep.Verify(repos => repos.Find(), Times.Exactly(1));

答案 1 :(得分:0)

您为FindAll设置了期望值,但随后调用了Find