无法使用powermokito模拟安全管理器

时间:2017-09-27 10:22:06

标签: java unit-testing mocking mockito powermock

通过查看Lauri@RunWith(PowerMockRunner.class) @PrepareForTest(System.class) public class TestClass { @Test public void testcheckSecurity() { //mocking the System class PowerMockito.mockStatic(System.class); SecurityManager secMan = PowerMockito.mock(SecurityManager.class); PowerMockito.when(System.getSecurityManager()).thenReturn(secMan); List<String> allowedClasses = Arrays.asList("ClassA", "ClassB", "ClassC", "ClassD"); BaseUtils.checkSecurity(allowedClasses); } } 写的答案,我通过嘲笑安全经理写了一个单元测试。以下是测试用例

public class BaseUtils{    
public static void checkSecurity(List<String> allowedClasses) {
        SecurityManager secMan = System.getSecurityManager();
        if (secMan != null) {
            StackTraceElement[] trace = Thread.currentThread().getStackTrace();
            String callingClass = trace[3].getClassName();
            if (!allowedClasses.contains(callingClass)) {
                secMan.checkPermission(new ManagementPermission("control"));
            }
        }
    }
}

这是测试下面的静态方法

secMan

但是当我调试测试用例时,checkSecurity(List<String> allowedClasses)方法中的SecurityManager let names = "Steve Jobs Nojobs".components(separatedBy: " ") let firstName = names.first! let lastName = names.dropFirst().joined(separator: " ") print(firstName)//Steve print(lastName)//Jobs Nojobs 为空。

我做错了什么?请帮我解决这个问题。

提前致谢

1 个答案:

答案 0 :(得分:1)

您必须将BaseUtils.class添加到@PrepareForTest而不是System.class,例如@PrepareForTest(BaseUtils.class)

您可以在documentation中找到更多信息,并解释为什么要这样做,您可能会发现here