I'm writing jUnits and got stuck with the Lambda expressions.
Is there a way to mock anonymous function?
return retryTemplate.execute(retryContext -> {
return mockedResponse;
});
In the above code, I'm trying to mock retryTemplate.
retryTemplate is of type - org.springframework.retry.support.RetryTemplate
For me the solution of @encrest didn't work.
RetryTemplate mockRetryTemplate = Mockito.mock(RetryTemplate.class);
Mockito.when(mockRetryTemplate.execute(Matchers.any(RetryCallback.class))).thenReturn(mockedResponse);
I got this error:
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
3 matchers expected, 1 recorded:
-> at test1(ServiceTest.java:41)
This exception may occur if matchers are combined with raw values:
//incorrect:
someMethod(anyObject(), "raw String");
When using matchers, all arguments have to be provided by matchers.
For example:
//correct:
someMethod(anyObject(), eq("String by matcher"));
For more info see javadoc for Matchers class.
at org.springframework.retry.support.RetryTemplate.execute(RetryTemplate.java:164)
This error seems a bit stupid, because .execute() should work with only 1 argument (and thus 1 matcher). See also non-sensical.
When looking into RetryTemplate sources, there are 4 .execute() methods. With one with 3 arguments. So I guess it is related to Matchers not being able to stub the right method.
Final solution:
RetryTemplate mockRetryTemplate = Mockito.mock(RetryTemplate.class);
Mockito.when(mockRetryTemplate.execute(Matchers.any(RetryCallback.class), Matchers.any(RecoveryCallback.class), Matchers.any(RetryState.class))).thenReturn(mockedResponse);
Can I add this to the original question: Why isn't the Matcher able to resolve to the one-argument method?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With