Thursday, January 12, 2012

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

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.
  
class GenericConstruct{
 
 public String doSomethingGeneric(){
  return "I do something";
 }
 
 public String doSomethingElseGeneric(){
  return "I do something else generic";
 }
}

class SubTypeOfGeneric extends GenericConstruct{
 
 public String doSomethingExtra(){
  System.out.println(doSomethingGeneric());
  System.out.println(doSomethingEleseGeneric());
  return "this is a very extra thing I am doing";
 }
 
}

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

import static org.junit.Assert.*;

import org.junit.Test;
import org.mockito.Mockito;

public class TheTest {

 @Test
 public void test() {
  SubTypeOfGeneric aSpy = Mockito.spy(new SubTypeOfGeneric());
  Mockito.doReturn("a random value").when((GenericConstruct)aSpy).doSomethingGeneric();
  Mockito.doReturn("another random value").when((GenericConstruct)aSpy).doSomethingElseGeneric();
  
  String result =aSpy.doSomethingExtra();
  assertTrue(!result.isEmpty());
  
 }
}


Happy mocking!

No comments:

Post a Comment