繁体   English   中英

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

[英]While mocking a static method with PowerMockito, I am getting Unfinished stubbing detected exception

下面是我的代码。 我有两个班

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

参考模拟静态方法

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM