Skip to content

Instantly share code, notes, and snippets.

@ishaaq
Created May 6, 2011 04:59
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ishaaq/958470 to your computer and use it in GitHub Desktop.
Save ishaaq/958470 to your computer and use it in GitHub Desktop.
Mockito doAnswer() callbacks
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.testng.Assert;
import org.testng.annotations.Test;
public class MyUnitTest {
int executions;
class ServiceA {
final ServiceB runner;
ServiceA(final ServiceB runner) {
this.runner = runner;
}
public void execute(Runnable runnable) {
runner.run(runnable);
}
}
interface ServiceB {
public void run(final Runnable runnable);
}
@Test
public void testCallbackInvokedOnlyOnce() {
ServiceB singleRunService = Mockito.mock(ServiceB.class);
// mock up the first callback to serviceB:
Mockito.doAnswer(new Answer<Void>(){
public Void answer(InvocationOnMock invocation) throws Throwable {
System.out.println("Running first time");
((Runnable)invocation.getArguments()[0]).run();
return null;
}
}).when(singleRunService).run(Mockito.isA(Runnable.class));
// mock up the second callback - it should not run:
Mockito.doAnswer(new Answer<Void>(){
public Void answer(InvocationOnMock invocation) throws Throwable {
System.out.println("cannot run second time");
return null;
}
}).when(singleRunService).run(Mockito.isA(Runnable.class));
ServiceA serviceA = new ServiceA(singleRunService);
serviceA.execute(new Runnable(){ public void run(){ executions++; } });
serviceA.execute(new Runnable(){ public void run(){ executions++; } });
Mockito.verify(singleRunService);
Assert.assertEquals(executions, 1, "The service should have run exactly once."); // this assert fails - executions = 0
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment