Skip to content

Instantly share code, notes, and snippets.

@deskid
Last active August 1, 2016 14:24
Show Gist options
  • Select an option

  • Save deskid/915035927522de69b0b57feda7dce27e to your computer and use it in GitHub Desktop.

Select an option

Save deskid/915035927522de69b0b57feda7dce27e to your computer and use it in GitHub Desktop.
mocking of callback function
ArrayList<Entity> list = new ArrayList<Entity>();
someObject.someMethod(p1, p2, new InnerInterface<Entity>() {
@Override
public boolean onEntry(Entity entity)
{
//some logic
legs.add(entry);
return true;
}
});
doAnswer(
new Answer<Void>() {
@Override
public Void answer(final InvocationOnMock invocation) throws Throwable {
InnerInterface<Entity> callback = (InnerInterface<Entity>) invocation.getArguments()[2];
callback.onEntry(strategyLeg);
return null;
}
}
).when(mockObject).someMethod(any(P1Param.class), any(P2Param.class), any(InnerInterface.class));
@Test
public void testDoSomethingAsynchronouslyUsingArgumentCaptor() {
// Let's call the method under test
dummyCaller.doSomethingAsynchronously();
final List<String> results = Arrays.asList("One", "Two", "Three");
// Let's call the callback. ArgumentCaptor.capture() works like a matcher.
verify(mockDummyCollaborator, times(1)).doSomethingAsynchronously(
dummyCallbackArgumentCaptor.capture());
// Some assertion about the state before the callback is called
assertThat(dummyCaller.getResult().isEmpty(), is(true));
// Once you're satisfied, trigger the reply on callbackCaptor.getValue().
dummyCallbackArgumentCaptor.getValue().onSuccess(results);
// Some assertion about the state after the callback is called
assertThat(dummyCaller.getResult(), is(equalTo(results)));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment