As @staszko032 already pointed out, your problem is not the lambda, your problem are static method calls - which are often a pain in the... behind to test. As long as Wrapper.wrap
(or, more likely, Otherclass.doSomething()
) is a static call, you need complicated tools like PowerMockito. You cannot expect throwing static calls around and still get well testable code - that's not how it works, sorry. Personally, I tend to say that PowerMockito is a tool used to solve problems you only have because the code is bad. Refactoring (if possible) should always be preferred to PowerMockito or similar tools.
So, personally, I would refactor it, for example by making the Wrapper class not static but instead inject an instance into it. This way, you can inject a mock in your test.
Of course, this will not actually solve your problem, since then you can verify that wrap(...) was called and you can even get your hands on the lambda which was given as a parameter, but the lambda will again call Otherclass.doSomething()
, which is again hard to test. So doing the refactoring here might be the better idea: Inject an instance of Otherclass instead of that static call, use a mock in your test and bingo, you can verify that doSomething
was called:
public class MyClass {
private OtherClass otherClassInstance; // setter/constructor/autowire/whatever
public Response someMethod() {
Response response = Wrapper.wrap( () -> {
return otherClassInstance.doSomething(); // now that's testable
});
// .... do something else ....
return Response;
}
}