Skip to content

Instantly share code, notes, and snippets.

@Cepr0
Last active July 9, 2020 19:55
Show Gist options
  • Save Cepr0/efe3eb3df042e405ebdf4a91a9197488 to your computer and use it in GitHub Desktop.
Save Cepr0/efe3eb3df042e405ebdf4a91a9197488 to your computer and use it in GitHub Desktop.
Example of Mockito ResultCaptor
@SpyBean private IdGenerator idGenerator;
@Autowired private SomeService service;
@Test
void createSubscription() {
SomeRequest request = new SomeRequest("name");
ResultCaptor<String> idCaptor = new ResultCaptor<>();
doAnswer(idCaptor).when(idGenerator).generate();
SomeResponse response = service.createResponse(request);
assertThat(response.getId()).isEqualTo(idCaptor.getResult());
}
public static class ResultCaptor<T> implements Answer<T> {
private T result = null;
public T getResult() {
return result;
}
@SuppressWarnings("unchecked")
@Override
public T answer(InvocationOnMock invocationOnMock) throws Throwable {
result = (T) invocationOnMock.callRealMethod();
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment