How to Mock a ZonedDateTime with Mockito and Junit

Viewed 2063

I need to mock a ZonedDateTime.ofInstant() method. I know there are many suggestions in SO but for my specific problem, till now I did not get any simple way out.

Here is my code :

public ZonedDateTime myMethodToTest(){

    MyClass myClass;
    myClass = fetchSomethingFromDB();
    try{
        final ZoneId systemDefault = ZoneId.systemDefault();
        return ZonedDateTime.ofInstant(myClass.getEndDt().toInstant(), systemDefault);
    } catch(DateTimeException dte) {
        return null;
    }
    
}

Here is my incomplete Test method :

 @Mock
 MyClass mockMyClass;

 @Test(expected = DateTimeException.class)
 public void testmyMethodToTest_Exception() {
    String error = "Error while parsing the effective end date";
    doThrow(new DateTimeException(error)).when(--need to mock here---);
    ZonedDateTime dateTime = mockMyClass.myMethodTotest();
}

I want to mock the ZonedDateTime.ofInstant() method to throw a DateTimeException while parsing for the negative scenario. How I can do that.

2 Answers

As of now (18/03/2022) Mockito supports mocking static methods. You can do

@Test
public void testDate() {
    String instantExpected = "2022-03-14T09:33:52Z";
    ZonedDateTime zonedDateTime = ZonedDateTime.parse(instantExpected);

    try (MockedStatic<ZonedDateTime> mockedLocalDateTime = Mockito.mockStatic(ZonedDateTime.class)) {
        mockedLocalDateTime.when(ZonedDateTime::now).thenReturn(zonedDateTime);

        assertThat(yourService.getCurrentDate()).isEqualTo(zonedDateTime);
    }
}

Please note that you need to use mockito-inline dependency:

    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-inline</artifactId>
        <version>4.4.0</version>
    </dependency>

You cannot use Mockito for this because ZonedDateTime is a final class and ofInstant is a static method, but you can use the PowerMock library to enhance Mockito capabilities:

final String error = "Error while parsing the effective end date";
// Enable static mocking for all methods of a class
mockStatic(ZonedDateTime.class);
PowerMockito.doThrow(new DateTimeException(error).when(ZonedDateTime.ofInstant(Mockito.anyObject(), Mockito.anyObject()));
Related