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.

4 comments:

Piotr Paradzinski said...

Thanks. Handy advice and clearly presented egzample.

Regards

Unknown said...

Thanks this was very helpful. Its exactly the sort of thing I've done in other frameworks like Mocha for Ruby.

Anonymous said...

Java is a word and not an acronym

Unknown said...

Very helpful...:)