'Mock call to static method of a utility class

I need to write a unit test for the method processNotification. But this method internally calls JsonUtility.getNotificationDTOFromMessage.

I need the return value to be null when this is called. How can we achieve this by using Mockito?

I cannot make changes in the code as it is not owned by me.

@Override
public void processNotification(String message) throws IOException {
    logger.info(" Processing the notifications");
    NotificationDTO notification = 
    JsonUtility.getNotificationDTOFromMessage(message);
    if (null == notification) {


Solution 1:[1]

You can’t mock static method by using Mockito. Try using the PowerMockito if you need to mock static methods

Ex: PowerMockito.mockStatic(JsonUtility.class);

Solution 2:[2]

You can't mock static metods using mockito.But you can manipulate your input data if possible, so that it will go into static method and return the value you want.you can pass message = null from your test method if possible.So that you can test your method.

Solution 3:[3]

Now newer version of Mockito supports static method mocking. No need to use PowerMockito Just Upgrade your version to 3.4.0 +

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Prathiksha G C
Solution 2 indhu
Solution 3 Onkar Patil