Home  >  Article  >  Java  >  Can Mockito Mock Abstract Classes?

Can Mockito Mock Abstract Classes?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-02 13:30:03981browse

Can Mockito Mock Abstract Classes?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn