Mocking lambda in rhino mocks

柔情痞子 提交于 2019-12-05 19:25:56

In a unit test, you have the system under test (SUT) and its collaborators. The goal of mocking is to replace the collaborators by something that you have full control over. That way you can set up different test cases and you can focus on testing just the behavior of the system under test, and nothing else.

In this case, I assume the rep object is the SUT. The lambda that you pass to the SUT's Find method could be considered a collaborator. Since you already have full control over that lambda, it doesn't really make sense to try to mock it with Rhino Mocks.

I'll try to give an example of unit test involving Rhino Mocks and lambdas anyway ;-) This is an example test which creates a predicate stub that always returns false, and which verifies that the Find method actually invoked that predicate:

[Test]
public void Find_returns_nothing_if_predicate_always_false()
{
   var predicateStub = MockRepository.GenerateStub<Func<Entity,bool>>();
   predicateStub.Stub(x => x(Arg<Entity>.Is.Anything)).Return(false);

   var repository = new Repository();
   var entities = repository.Find(predicateStub);

   Assert.AreEqual(0, entities.Count(), 
      "oops, got results while predicate always returns false");
   predicateStub.AssertWasCalled(x => x(Arg<Entity>.Is.Anything));
}

Of course, as in your own example, you don't really need Rhino Mocks here. The whole point of the lambda syntax is to make it easy to provide an implementation in-place:

[Test]
public void Find_returns_nothing_if_predicate_always_false()
{
   bool predicateCalled = false;
   Func<Entity,bool> predicate = x => { predicateCalled = true; return false; };

   var repository = new Repository();
   var entities = repository.Find(predicate);

   Assert.AreEqual(0, entities.Count(), 
      "oops, got results while predicate always returns false");
   Assert.IsTrue(predicateCalled, "oops, predicate was never used");
}
Coppermill

Found the answer I was after

repository.Expect(action => action.Find<Entity>(x => x.ID == 0))
          .IgnoreArguments()
          .Return(entities)
          .Repeat
          .Any();

this way we can't come out..because due to the IgnoreArguments(),it will never go inside and see the value of arguments and we will pass through. But the major problem with this approach is writing the AssertWasCalled(some lambda expression) is not possible because now in the Assert part it is showing error like ExpectaionViolationException was unhandled by user code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!