An Easy Way to Test Abstract Classes with Mockito

Garston Tremblay
CA\rABU Life
Published in
2 min readApr 5, 2016

One problem that you may have encountered when attempting to write a test for an abstract class is that, well, you can’t instantiate it. So how do you test it?

I was wondering the same thing a few weeks ago. I had the following abstract class (simplified for readability and understanding):

public abstract class MyAbstractClass {
protected String getDefaultOrder() {
return getDefaultFetch().split(",")[0];
}
protected abstract String getDefaultFetch();
}

I wanted to write a simple test that would verify that getDefaultOrder() would perform as expected and return the first word in the comma-delimited string returned by getDefaultFetch().

Luckily, I stumbled upon Mockito’s thenCallRealMethod() method. This made the test easy to write:

public void defaultOrderShouldBeFirstWordInDefaultFetch() {
MyAbstractClass abstractClass = mock(MyAbstractClass.class);
when(abstractClass.getDefaultFetch()).thenReturn(
"Rank,FormattedID,Name,PlanEstimate,Priority,Owner,ClosedDate,CreationDate"
);
when(abstractClass.getDefaultOrder()).thenCallRealMethod();
assertEquals(abstractClass.getDefaultOrder(), "Rank");
}

As you can see, we’re telling Mockito that when the getDefaultOrder() method gets called on the mock object “abstractClass”, Mockito should execute the real getDefaultOrder() defined in our MyAbstractClass class. This is contrary to Mockito’s default behavior of simply returning the default value for the return type of the method called on the mock object (in this case, for getDefaultOrder()’s return type of String, Mockito would return null).

So there you go: an easy way to test methods in abstract classes!

--

--