This question has gotten a lot of traction, and Mockito has improved a lot since 2012. PowerMockito has been unmaintained since 2020, and most of PowerMockito's functionality has been migrated into Mockito since v4+ in 2024. This includes mocking constructor functions using Mockito v4+.
Note that for Mockito v4+, you will need to manually import the mockito-inline
dependency in your pom file (Mockito v5+ uses the inline maker by default, so no need to change your pom file):
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-inline</artifactId>
<scope>test</scope>
</dependency>
For mocking the Date
constructor, you don't need to restructure your code to inject Date anymore as @munyengm's answer mentions. Mockito has a dedicated mockConstruction
method now. Here's an MVE:
MyService.java
class MyService {
public Date generateDate() {
return new Date();
}
}
MyServiceTest.java
@ExtendWith(MockitoExtension.class)
class MyServiceTest {
MyService myService = new MyService();
@Test
void testGenerateDate() {
try(var __ = mockConstruction(Date.class, (mock, ctx) -> when(mock.getTime()).thenReturn(1000L))) {
var nextDate = myService.generateDate();
assertEquals(new Date(1000L).getTime(), nextDate.getTime());
}
}
}
The mockConstruction
method tells Mockito to make a mock Date
object whenever the Date constructor gets called. Then the only thing we need to do is define stubs for whatever behavior we want the class to simulate when its methods are called.
In the above example, I am telling the Date mock to return 1000L
for the time whenever the mock object's getTime()
method gets called.
There are other variations of the mockConstruction
method that are worth looking into for more complex scenarios, such as returning a different response each time getTime()
is called. More info is available in this Baeldung article.