0 votes
1 view
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 (46.1k 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.

Citation:

public abstract class My {

  public Result methodUnderTest() { ... }

  protected abstract void methodIDontCareAbout();

}

public class MyTest {

    @Test

    public void shouldFailOnNullIdentifiers() {

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

        Assert.assertSomething(my.methodUnderTest());

    }

}

 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.

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...