Ketan's Musings

Where he blogs about his eclipse musings

Mockito – one of the better mocks

with 2 comments

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.

Written by Ketan

March 5th, 2008 at 7:24 pm

Posted in Java,Open Source

Tagged with , , ,

2 Responses to 'Mockito – one of the better mocks'

Subscribe to comments with RSS or TrackBack to 'Mockito – one of the better mocks'.

  1. Very Cool, looks much cleaner!

    Nirav Thaker

    5 Mar 08 at 8:30 pm

  2. I like Mockito too!

    Jertix

    1 Apr 08 at 7:07 pm

Leave a Reply

IMPORTANT! To be able to proceed, you need to solve the following simple math (so we know that you are a human) :-)

What is 9 + 15 ?
Please leave these two fields as-is: