0

Below is my code. I have two class

1)
public class AdminUtil {
 public static boolean isEnterpriseVersion() {
        return SystemSettings.getInstance().isEnterpriseVersion();
    }
}
----
2)
public class SystemSettings {
public static synchronized SystemSettings getInstance() {
        if (systemSettings == null) {
            systemSettings = new SystemSettings();
        }
        return systemSettings;
    }
}

And this is how i am trying to mock isEnterpriseVersion() method of AdminUtil class . (I have added @PrepareForTest({SystemSettings.class, AdminUtil.class}) on top of test class)

PowerMockito.mockStatic(SystemSettings.getInstance().getClass());
        PowerMockito.doReturn(systemSettings).when(SystemSettings.class, "getInstance");
        PowerMockito.mockStatic(AdminUtil.class);
        PowerMockito.doReturn(true).when(AdminUtil.class, "isEnterpriseVersion");

Its throwing below exception...

    org.mockito.exceptions.misusing.UnfinishedStubbingException: 
    Unfinished stubbing detected here:
    -> at org.powermock.api.mockito.internal.PowerMockitoCore.doAnswer(PowerMockitoCore.java:36)

E.g. thenReturn() may be missing.
Examples of correct stubbing:
    when(mock.isOk()).thenReturn(true);
    when(mock.isOk()).thenThrow(exception);
    doThrow(exception).when(mock).someVoidMethod();
Hints:
 1. missing thenReturn()
 2. you are trying to stub a final method, you naughty developer!
ritesh kumar
  • 81
  • 1
  • 7
  • You are mocking it incorrectly – Nkosi Oct 10 '18 at 19:57
  • You might need to use the `when().thenReturn()` syntax, see https://stackoverflow.com/questions/20353846/mockito-difference-between-doreturn-and-when/20360269 – Progman Oct 10 '18 at 19:58

1 Answers1

0

The call to

PowerMockito.mockStatic(SystemSettings.getInstance().getClass())

is invoking the actual static member.

You need to change up how you arrange the mocks

boolean expected = true;
//create mock instance
SystemSettings settings = PowerMockito.mock(SystemSettings.class);    
//setup expectation
Mockito.when(settings.isEnterpriseVersion()).thenReturn(expected);

//mock all the static methods
PowerMockito.mockStatic(SystemSettings.class);
//mock static member
Mockito.when(SystemSettings.getInstance()).thenReturn(settings);

So now a call to

boolean actual = AdminUtil.isEnterpriseVersion();

should return true.

Reference Mocking Static Method

Nkosi
  • 235,767
  • 35
  • 427
  • 472
  • Tried this now getting below exception. org.mockito.exceptions.misusing.MissingMethodInvocationException: when() requires an argument which has to be 'a method call on a mock'. For example: when(mock.getArticles()).thenReturn(articles); on line PowerMockito.when(SystemSettings.getInstance()).thenReturn(settings); – ritesh kumar Oct 10 '18 at 20:09
  • Sorry, tired again getting same error. its expecting a a method call on a mock', and looks not able to identify "SystemSettings" as mocked object. – ritesh kumar Oct 10 '18 at 20:33