Mock Objects

When testing it’s pretty common to see the need for mocking a certain object, say, a Data Access Ojbect. This way you don’t need to depend on a database and you can focus on the actual logic implemented by the method being tested.

For that you have several alternatives like creating the Mock class by hand or - and this is the more common - use one of the various mocking libraries out there.

They all look the same but the past couple of days I’ve come accross to a new - at least for me - mocking library for Java. It’s called Mockito. As the creators state, technically, Mockito is a fork of EasyMock.

I have used EasyMock already but I do think Mockito has its advantages. I find it clear and a bit less verbose to write.

From one of the stubbing examples on their website:


//You can mock concrete classes, not only interfaces
LinkedList mockedList = mock(LinkedList.class);

//stubbing - before execution
stub(mockedList.get(0)).toReturn("first");

//following prints "first"
System.out.println(mockedList.get(0));

//following prints "null" because get(999) was not stubbed
System.out.println(mockedList.get(999));

Looking forward to using it in production! ;)

Comments