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:
Mock the Abstract Class:
<code class="java">My mock = Mockito.mock(My.class, Answers.CALLS_REAL_METHODS);</code>
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.
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>
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>
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!