Mocking lambda in rhino

I'm trying to use Rhino Mocks to make fun of the next lambda, but keep hitting the brick wall.

var result = rep.Find<T>(x => (x as IEntity).ID == (entity as IEntity).ID).FirstOrDefault(); 

Any ideas?

+4
source share
3 answers

Found the answer that I received after

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

In unit test, you have a system under test (SUT) and its employees. The purpose of the ridicule is to replace co-authors with the fact that you have full control over. Thus, you can set up various test cases, and you can focus on testing only the behavior of the system under test and nothing more.

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

I will try to give an example unit test involving Rhino Mocks and lambdas anyway ;-) This is an example test that creates a stub predicate that always returns false and that checks if the Find method really does this 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 do not need Rhino Mocks here. The whole point of lambda syntax is to simplify in-place implementation implementation:

 [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"); } 
+5
source

Thus, we will not be able to exit due to IgnoreArguments (), it will never go inside and see the value of the arguments, and we will pass. But the main problem with this approach is writing AssertWasCalled (some kind of lambda expression) is impossible, because now an error is displayed in the Assert part, since the ExpectaionViolationException is not processed by the user code

0
source

Source: https://habr.com/ru/post/1306255/


All Articles