Skip to content

Instantly share code, notes, and snippets.

@pzentenoe
Last active September 15, 2017 15:47
Show Gist options
  • Save pzentenoe/9bd34b6a993bfb619065753605efcbf1 to your computer and use it in GitHub Desktop.
Save pzentenoe/9bd34b6a993bfb619065753605efcbf1 to your computer and use it in GitHub Desktop.
Uso de 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