在使用PowerMockito模拟静态方法时,出现未完成的存根检测到异常

时间:2018-10-10 19:47:31

标签: java mockito powermockito

下面是我的代码。我有两节课

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;
    }
}

这就是我试图模拟AdminUtil类的isEnterpriseVersion()方法的方式。 (我在测试类的顶部添加了@PrepareForTest({SystemSettings.class,AdminUtil.class}))

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

它抛出异常...

    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!

1 个答案:

答案 0 :(得分:0)

致电

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

正在调用实际的静态成员。

您需要更改模拟的排列方式

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);

现在致电

boolean actual = AdminUtil.isEnterpriseVersion();

应返回true

引用Mocking Static Method