Blog About Contact

Testing Abstract Classes With Mockito and JUnit

Published Tue, 28 Jul 2009 • 3 comments

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.


About the Author

Richard Nichols is an Australian software engineer with a passion for making things.

Follow him on twitter or subscribe by RSS or email.

You might also enjoy reading -


Discuss / Comment

There are 3 comments.

Add a comment

  • {{e.error}}

Thanks for your comment!/

Required.
Valid email address required.
Required.
Posting message, please wait...