Using Mockito With JUnit3


I’ve recently been stuck in Java 1.4 land, and have to deal with the great sadness that comes with no generics, no annotations, and none of the other niceties that Java5 provides. One of the things I had been missing is not having Mockito, and I’d prefer not using EasyMock or JMock because the 1.4 versions of them are even noisier than the current ones!

Luckily, it looks like Mockito runs just fine with Java 1.4. But for clear, easier to read tests, I’ve found this quick TestCase subclass useful:

public class MockitoTestCase extends TestCase {
	public Object mock(Class clazz){
		return Mockito.mock(clazz);
	}

	public OngoingStubbing when(Object o){
		return Mockito.when(o);
	}

	public Object verify(Object o){
		return Mockito.verify(o);
	}

	public List verify(List o){
		return (List)Mockito.verify(o);
	}

	public BDDMyOngoingStubbing given(Object o){
		return BDDMockito.given(o);
	}
}

This way, I can write class level specifications (or unit tests) like this:

public class MockitoWorksWithJunit3Test extends MockitoTestCase {
	public void testGivenSyntax(){
		List aList = (List) mock(List.class);

		when(aList.get(3)).thenReturn("Hello Dude");

		assertEquals("Hello Dude", aList.get(3));
	}

	public void testVerifications(){
		List aList = (List) mock(List.class);
		Dude dude = new Dude();

		dude.addSomeThingToThisList(aList);

		verify(aList).add("stuff");
	}
}

class Dude{
	public void addSomeThingToThisList(List stuff){
		stuff.add("stuff");
	}
}

Nifty. I think I can survive a bit now. ;)

You can leave a response, or trackback from your own site.

Facebook comments:

One Response to “Using Mockito With JUnit3”

Leave a Reply

Subscribe to RSS Feed Follow me on Twitter!