Mocking Abstract Classes with Mockito
When testing abstract classes, manually crafting mocks can be inconvenient. Mockito provides a more efficient solution.
Query:
Is it possible to mock an abstract class using Mockito rather than manual mock creation? If so, how?
Answer:
Mockito offers the option to mock abstract classes without creating a concrete subclass. Using Mockito.mock(My.class, Answers.CALLS_REAL_METHODS), you can create a partial mock where the abstract methods are handled by the mock itself.
For example:
<code class="java">public abstract class My { public Result methodUnderTest() { ... } protected abstract void methodIDontCareAbout(); } public class MyTest { @Test public void shouldFailOnNullIdentifiers() { My my = Mockito.mock(My.class, Answers.CALLS_REAL_METHODS); Assert.assertSomething(my.methodUnderTest()); } }</code>
Note that with CALLS_REAL_METHODS, all actual methods are executed unless explicitly overridden in the test. This approach provides greater flexibility than using a spy, which requires instantiating a subclass of the abstract class.
The above is the detailed content of Can Mockito Mock Abstract Classes?. For more information, please follow other related articles on the PHP Chinese website!