Home > Java > javaTutorial > body text

How to Test Abstract Classes with Mockito: A Step-by-Step Guide

Susan Sarandon
Release: 2024-10-30 18:07:03
Original
530 people have browsed it

How to Test Abstract Classes with Mockito: A Step-by-Step Guide

Testing Abstract Classes with Mockito

Abstract classes pose challenges for unit testing due to their lack of concrete implementations. While manual mock creation is an option, it can be time-consuming and complex.

Mockito offers an elegant solution for testing abstract classes without manual mock creation. Here's how it works:

  1. Mock the Abstract Class:

    <code class="java">My mock = Mockito.mock(My.class, Answers.CALLS_REAL_METHODS);</code>
    Copy after login

    By using Answers.CALLS_REAL_METHODS, you instruct Mockito to execute the actual implementation of non-overridden methods, allowing you to test the behavior of the abstract methods.

  2. Stub Abstract Methods as Needed:

    For abstract methods that you want to control during testing, use the following syntax:

    <code class="java">Mockito.when(mock.methodIDontCareAbout()).thenReturn(null);</code>
    Copy after login

    This stubs the specific abstract method, providing the desired behavior.

Example:

Consider the following scenario:

<code class="java">public abstract class My {
    public Result methodUnderTest() { ... }
    protected abstract void methodIDontCareAbout();
}

@Test
public void shouldFailOnNullIdentifiers() {
    My my = Mockito.mock(My.class, Answers.CALLS_REAL_METHODS);
    Assert.assertSomething(my.methodUnderTest());
}</code>
Copy after login

In this example, the abstract method methodIDontCareAbout() is not used in the method under test. By mocking it with thenReturn(null), you effectively ignore it during testing.

This approach provides a concise and convenient way to test abstract classes, eliminating the need for hand-crafted mocks and facilitating efficient testing of non-concrete classes.

The above is the detailed content of How to Test Abstract Classes with Mockito: A Step-by-Step Guide. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!