Tuesday, April 20, 2010

Mocking the Lambda Expression method

Today, when trying to unit testing for some code in Specification class, I just found that "It's very difficult to mock the Lambda Expression in code". But I also try mocking it in 2 hours and I mocked it perfectly (:D). And my work start now

+ First thing I have the class as:

As you see the red rectangle, we have the Lambda Expression like this Expression<...>>, so we must to mock it for unit testing (I used Rhino Mock for mocking object in my test fixture). And now I want to show you the UserRespository class as below:

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.

1 comment:

  1. 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.

    The 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):

    .Setup(x => x.Find(ThatHas.AnExpressionFor()

    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/