Using MOQ and a Generic Repository. I'm not able to successfully test the following method.

[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);

    }

It's calling this Method:

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

My Generic Repository has the following:

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

I get the following:

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

解决方案

You haven't provided the full method signature of IRepository<T> Find(), but at a guess, it is something like IQueryable<T> Find(). Because we want to mock it to return a small amount of fake data, it doesn't really matter that we just bind it to an in memory List. Because the SUT performs a filter (Active), ensure that you also provide unwanted data in the fake data to ensure that the SUT's filtering logic is working correctly.

Assuming all of this, your setup would look something like:

 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());

Your Act + Assert would then be something like:

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));

其他提示

You set up an expectation for FindAll but then called Find.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top