开发者

How can I call setup in Moq twice in one method?

I have a unit test method that needs to mock (stub?) two repository method calls in the class that I'm testing. Every example I've worked through until now shows one setup method for the Mock, but now I need two.

Example:

_employeeRepositoryMock.Setup(e => e.GetEmployees())
            .Returns(new Employee[]
                     {
                        new Employee
                        {
                            Name = "John Doe"
                        }
                     });
_employeeRepositoryMock.Setup(e => e.UpdateEmployee(1)).Returns(true);

Assert.IsTrue(_employeeService.UpdateEmployeeRecords() > 0);
_employeeRepositoryMock.Verify(gr => gr.UpdateEmployee(1), Times.Exactly(1));

In this example I need to mock two repository methods that are both called in "UpdateEmployeeRecords()" but I'm not sure how.

Update

Scratch this entire question -- I overlooked something simple. I was passi开发者_运维知识库ng in the wrong numerical value for UpdateEmployee which was causing the Assert to fail. I changed the parameter in the mock to It.IsAny instead to get it to pass.


You can do it this way by creating the type of data the method should return (in my case a List<int> and a List<string>) and return it using the .Returns. Now whenever the DoSomething() method is called it will return my intResult List as the mocked data and the stringResult List when the DoSomethingElseThatIsReallyCool() method is called:

//Test method
{
  List<int> intResult = new List<int>();
  intResult.Add(0);

  List<string> stringResult = new List<string>();
  stringResult.Add("test");

  _reposMock.Setup(r=>r.DoSomething()).Returns(intResult);
  _reposMock.Setup(r=>r.DoSomethingElseThatIsReallyCool()).Returns(stringResult);

  Assert.IsTrue(_reposMock.SomeMethod() > 0);
}


Your setup methods appear to be fine. Your Assertion must be failing for some other reason. Some thoughts:

  1. Have you tried debugging your test to see what's going on?
  2. Is 1 the correct value to be mocking in your UpdateEmployee method?
  3. (Pardon me if this is patronizing, but I've done this before) Are you passing your mock to your service via _employeeRepositoryMock.Object?
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜