下面是我的代码。我有两个班级
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!
对
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
.
引用模拟静态方法