+ First thing I have the class as:
As you see the red rectangle, we have the Lambda Expression like this Expression
Don't refuse about that, we only demonstrated about this function for my post. Don't care about other code in this function. We shall pass the Lambda Expression (LE) for executing in run time. So how do you mock this LE? It's not secret for anyone, and now I will show you about it
Pay attention to the red rectangle, I mocked the LE using Rhino Mock. As you see, it's very simple, we only supposed that the LE is not null and expected that if it's not null we shall return true for it. IMHO maybe have many methods for mocking the LE but anyway this is my working for it.
Using Rhino Mocks' `Arg<>.Is.NotNull` forces you to write code that's not covered by your test. Instead, it allows any query/expression at all to pass through, rendering your mock basically useless from a unit testing perspective.
ReplyDeleteThe solution: You either need to use .WhenCalled to capture the expression and test it directly OR you need to constrain your mock better. Either way is messy and difficult. I've dealt with this issue for as long as I've been practicing TDD. I finally threw together a helper class to make this a lot more expressive and less messy. Here's the end-result (adapted to your example):
mockPeopleRepository
.Setup(x => x.Find(ThatHas.AnExpressionFor()
.ThatMatches(correctPerson)
.And().ThatDoesNotMatch(deletedPerson)
.Build()))
.Returns(_expectedListOfPeople);
Here's the blog article that talks about it and gives the source code: http://awkwardcoder.com/2013/04/24/constraining-mocks-with-expression-arguments/