Tuesday, January 12, 2010

Partial mocks in Mockito - Mock only what you need, left the rest to the original class

In Mockito you can not only create "regular" mocks, but also partial mocks. Let's assume we need to use instance of class A, and we want to mock it. We can do mock:
A aMock = Mockito.mock(A.class);
Sometimes, we want to use instance of real class A, but mock only part of it. Only one or few methods. With Mockito it is possible:
A a = Mockito.spy(new A());
So we spy real object, we can verify it's method calls, but we can also do that:
Mockito.when(a.methodCall()).thenReturn(1);
We can mock some of A's methods, leaving the rest to the real A instance.
For me it was useful while I was creating test involving user. User object's have ID, but there is only getter for it. ID is always set by database, and should never been changed by programmers, so there is only getter. Thanks to partial mocks, I mocked only getId() method, without need to add setId() just for testing purposes.