Archive for the ‘mock’ tag
Mockito – one of the better mocks
Now that I’ve got your attention. Mockito is not just better than the other mock frameworks out there, it’s infact the best out there.
After reading a lot of noise from fellow ThoughtWorkers in the recent past about Mockito. I decided to give a yet another mock framework a try.
Here’s what I ended up writing:
public class RecorderLauncherTest extends TestCase {
private RecorderListener listener;
private RecorderLauncher launcher;
private TestRunner runner;
protected void setUp() throws Exception {
super.setUp();
listener = mock(RecorderListener.class);
runner = mock(TestRunner.class);
launcher = new RecorderLauncher(runner, listener);
}
public void testNotifiesListenerWhenLauncherStarts() throws Exception {
launcher.launch();
verify(listener).start();
}
public void testNotifiesListenerWhenExecutionFails() throws Exception {
stubVoid(runner).toThrow(new RuntimeException()).on().run();
launcher.launch();
verify(listener).start();
verify(listener).error();
}
public void testNotifiesListenerWhenExecutionCompletes() throws Exception {
launcher.launch();
verify(listener).start();
verify(listener).finish();
}
}
What’s even nicer is that it’s actual code and not strings, and refactoring tests do not break my mocks.
Good bye expect-run-verify, hello run-verify.
This looks, and reads far better than the JMock syntax, and it was love at first sight; I’m test-infested now. If you have not tried mockito as yet, I’d recommend that you do. I’m sure you’ll love it too.