Testing Abstract Classes With Mockito and JUnit

Often times in Java, you have an abstract parent class which has some concrete methods which call abstract methods which will be implemented by the child classes.

So what’s an easy way to test this sort of pattern?

A mock is not an appropriate solution, since we don’t want to mock our abstract class, we want to provide an implemention of the abstract methods, which we can mock to test the logic of the parent class.

There is a neat solution to this problem, using the great mocking framework for Java – Mockito -

public abstract class MyAbstract {
  public String concrete() {
    return abstractMethod();
  }

  public abstract String abstractMethod();
}

public class MyAbstractImpl extends MyAbstract {
  public String abstractMethod() {
    // we have to provide an implementation that will run without error
    return null;
  }
}

public class MyAbstractTest extends TestCase {

  public void testConcrete() {
    MyAbstractImpl abstractImpl = spy(new MyAbstractImpl());
    doReturn("Blah").when(abstractImpl).abstractMethod();
    assertTrue("Blah".equals(abstractImpl.concrete()));
  }
}

So what’s going on here?

Well Mockito (1.8+) implements a “spy” feature which doesn’t mock the object, it creates a “spy” wrapper around the real method implementations. This allows us to override the return values / exception behaviour of some methods, but leave other methods to implement their usual behaviour.

In the code above, we override the abstractMethod() which is part of the implementation class, to test the concrete() method in our abstract class. Of course, usually the abstract class would be doing something more interesting than simply returning the implementor’s value, and so we would implement tests in the ususal fashion to test the different code paths in our concrete() method.

Related posts:

  1. NetBeans 6.7 Broke My Parameterized Tests
  2. Unfortunately Interesting Java Generics
  3. Simple Guide To Sub-reports in JasperReports / iReport
  4. 5 Reasons Why NetBeans Rocks
  5. Clustering Guice Java Web Applications

This entry was posted in General, Java, Software Engineering and tagged Java, junit, mockito, testing. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>