Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking anonymous function

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

like image 839
user1879835 Avatar asked Dec 05 '25 05:12

user1879835


1 Answers

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?

like image 148
codesmith Avatar answered Dec 07 '25 18:12

codesmith