Last active
July 9, 2020 19:55
-
-
Save Cepr0/efe3eb3df042e405ebdf4a91a9197488 to your computer and use it in GitHub Desktop.
Example of Mockito ResultCaptor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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