lundi 23 février 2015

Unit test code with Java 8 Lambdas

I have been using Java 8 for some months, and I have started to use Lambda expressions, which are very convenient for some cases. However, I often come across some problems to unit test the code that uses a Lambda.


Take as an example the following pseudo-code:



private Bar bar;

public void method(int foo){
bar.useLambda(baz -> baz.setFoo(foo));
}


One approach would be to just verify the call on bar



verify(bar).useLambda(Matchers.<Consumer<Baz>>.any());


But, by doing that, I don't test Lambda's code.


Also note that I am not able to replace the Lambda with a method and use method reference:



bar.useLambda(This::setFooOnBaz);


Because I will not have the foo on that method. Or at least that is what I think.


Have you had this problem before? How can I test or refactor my code to test it properly?


Aucun commentaire:

Enregistrer un commentaire