Unit test code and Java 8 Lambdas
I've been using java 8 for several months, and I've started using lambda expressions, which is very convenient in some cases However, I often encounter some problems to unit test the code using lambda
Take the following pseudo code as an example:
private Bar bar; public void method(int foo){ bar.useLambda(baz -> baz.setFoo(foo)); }
One way is to verify the call at the bar
verify(bar).useLambda(Matchers.<Consumer<Baz>>.any());
However, by doing so, I will not test lambda's code
Also note that I cannot replace lambda with a method and use method reference:
bar.useLambda(This::setFooOnBaz);
Because I won't have this method foo Or at least that's what I think
Have you had this problem before? How do I test or refactor my code to test correctly?
edit
Since my coding is a unit test, I don't want to instantiate it, but I will use simulation So I can't just verify Baz Setfoo call
Solution
You can't unit test a lambda directly because it doesn't have a name There is no way to call it unless you have a reference
The usual alternative is to refactor lambda into a named method, use the method reference in the product code, and call the method by name from the test code As you said, this situation cannot be refactored in this way because it captures foo, and the only thing that can be captured by method reference is the receiver
However, answer from yshavit involves whether it is necessary to unit test private methods A lambda can be considered a private method
There is also a bigger point here One of the reasons for unit testing is that you do not need to unit test too simple to break This is very consistent with the ideal case of lambda. This is a very simple expression, which is obviously correct (at least that's what I think is ideal.) Consider this example:
baz -> baz.setFoo(foo)
There is no doubt that this lambda expression, when submitting a Baz reference, will call its setfoo method and pass it as a parameter to foo? Perhaps it is so simple that it does not require unit testing
On the other hand, this is just an example. Maybe the actual lambda you want to test is more complex I see code using large, nested, multiline Lambdas See this answer and its questions and other answers, for example Such a lamb is really difficult to debug and test If the code in a lambda is complex enough to be tested, the code should be refactored from the lambda so that it can be tested using conventional techniques