Links

Mocking constructors using Mockito

The Mockito inline mock maker is now able to mock constructor invocations (v3.5.0+). Diffblue Cover enables the user to specify potential classes for mocked construction with --mock-construction

Introduction

Since version 3.5.0 Mockito has provided the capability to mock constructor method invocations.
The mockConstruction method is the entrypoint for the mocking of constructors. In the example below the Date constructor is mocked:
public static long currentTime() {
return new Date().getTime();
}
@Test
public void testCurrentTime() {
// Arrange
try (MockedConstruction<Date> dateMocked = mockConstruction(Date.class, (mock, context) -> {
when(mock.getTime()).thenReturn(1_000_000_000_000L);
})) {
// Act
final long time = currentTime();
// Assert
Assertions.assertEquals(1_000_000_000_000L, time);
}
}
As you can see, the API for mocked construction is different from that used for creating instance mocks. Similar to static mocking, it is recommended to mock constructors within a try-with-resources statement.

Configuration

Construction mocking is only available if the inline mock maker is enabled in your project. To enable it, instead of using the mockito-core artifact, include the mockito-inline artifact in your project. The example below shows a detail from a Maven pom.xml:
<dependency>
<groupId>org.mockito</groupId>
<!--<artifactId>mockito-core</artifactId>-->
<artifactId>mockito-inline</artifactId>
<version>4.11.0</version>
<scope>test</scope>
</dependency>

Usage

To support the mocking of constructors the --mock-construction option has been added to Diffblue Cover. This allows the user to suggest the names of classes whose constructors should be mocked when unit testing. Diffblue Cover will mock the constructors of these suggested classes, and if those mocks prove valuable for test coverage they will be included in the resulting tests.
For example, in the example command line below, the user is suggesting that it may be useful to mock both the Foo constructors and the Bar constructors when creating tests for the class FooBarUser:
dcover create --mock-construction com.diffblue.Foo com.diffblue.Bar -- com.diffblue.FooBarUser
The -- argument is used to delimit the mock options from the target class prefix.
Diffblue Cover will issue warnings if the --mock-construction option is used in a project which does not support mocked construction - it will ignore the option and continue with test creation.