Explore Courses Blog Tutorials Interview Questions
0 votes
in Java by (10.2k points)
I'd like to test an abstract class. Sure, I can manually write a mock that inherits from the class.

Can I do this using a mocking framework (I'm using Mockito) instead of hand-crafting my mock? How?

1 Answer

0 votes
by (46k points)

The subsequent suggestion lets you test abstract classes without building a "real" subclass - the Mock is the subclass.

use Mockito.mock(My.class, Mockito.CALLS_REAL_METHODS), then mock any abstract rules that are requested.


public abstract class My {

  public Result methodUnderTest() { ... }

  protected abstract void methodIDontCareAbout();


public class MyTest {


    public void shouldFailOnNullIdentifiers() {

        My my = Mockito.mock(My.class, Mockito.CALLS_REAL_METHODS);




 The advantage of this resolution is that you do not have to implement the abstract methods, as long as they are nevermore invoked.

In my trustworthy viewpoint, this is neater than using a spy, since a spy requires an example, which indicates you have to create an instantiable subclass of your abstract class.

Browse Categories