Using Mockito Spy objects to test java objects/classes with inheritance (very simple example)

Share on:

I came across today a case where I needed to complete a unit-integration test of some quite complex enterprise Java code. Actually it was JSF backing bean with a specific inheritance chain, wired all together with some EJB's.

Mockito is my library of preference for all these kinds of tests (really lovely library and highly recommended). There is again an excellent post here with various comments. I just felt like providing a simplistic example + have a post to remind myself in the future.

The power of Mockito on such a scenario which actually can be something like - "I want to unit-integrate test something that inherits legacy code from super classes" is the use of Spy objects (see here as well). The power of Spy objects is that you can have a proper Mock object, but you are able to invoke some real methods as well. A mixture that is.

A very simple example with a super and a sub class.

 1class GenericConstruct{
 2
 3    public String doSomethingGeneric() { 
 4        return "I do something"; 
 5    }
 6
 7    public String doSomethingElseGeneric() { 
 8        return "I do something else generic"; 
 9    } 
10}
1class SubTypeOfGeneric extends GenericConstruct {
2
3    public String doSomethingExtra() {
4        System.out.println(doSomethingGeneric());
5        System.out.println(doSomethingEleseGeneric()); 
6        return "this is a very extra thing I am doing"; 
7    }
8}

The test, creates an actual spy, mocks the 2 methods inherited from the super() class and then goes on with the rest of the implementation.

 1
 2import static org.junit.Assert;
 3
 4import org.junit.Test;
 5import org.mockito.Mockito;
 6
 7public class TheTest {
 8
 9    @Test
10    public void test() {
11        SubTypeOfGeneric aSpy = Mockito.spy(new SubTypeOfGeneric());
12        Mockito.doReturn("a randomvalue").when((GenericConstruct) aSpy).doSomethingGeneric();
13        Mockito.doReturn("another randomvalue").when((GenericConstruct) aSpy).doSomethingElseGeneric();
14        String result = aSpy.doSomethingExtra();
15        assertTrue(!result.isEmpty());
16    }
17}

Happy mocking!