Mock specific method with mockito-inline not complete class

527 Views Asked by At

I want to mock static methods of a class. When I'm using mockito-inline, it mocks the complete class instead of mocking specific methods. My objective is that it should only mock method which I want it to be. Others should remain untouched (as it is).

@Test
     public void myTest() throws Exception {
         ZonedDateTime mockDateTime = ZonedDateTime.of(2022, 1, 1, 10, 10, 10, 100, ZoneId.of(DEFAULT_ZONE_ID));
          try (MockedStatic<ZonedDateTime> zonedTime = Mockito.mockStatic(ZonedDateTime.class)) {
              zonedTime.when(() -> ZonedDateTime.now(ZoneId.of(DEFAULT_ZONE_ID))).thenReturn(mockDateTime);

         // Zoned time will be called inside myMethod
            ZonedDateTime zonedDateTime = myClass.myMethod();
            System.out.println("Result: "+ zonedDateTime);
          }

In above code I'm mocking ZonedDateTime.now() method, but for some reason, other methods are getting mocked as well e.g ZonedDateTime.parse() etc, since I'm not giving any mocks for them, they're returning null for those un-mocked method. Ideally there usual implementation should work.

I'm looking for some change with which all original method should be inplace.

1

There are 1 best solutions below

0
On

As described in the documentation mocks return null/empty values by default. API for creating static spies which would include the default behavior by default is not currently defined, so you have to tell Mockito to call the actual methods on the mock either by calling when(...).thenCallRealMethod() or by using the CALLS_REAL_METHODS constant Answer when calling the mockStatic method:

try (MockedStatic<ZonedDateTime> zonedTime = Mockito.mockStatic(ZonedDateTime.class, CALLS_REAL_METHODS)) {
    // ...
}