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

Java 无法使用powermokito模拟安全管理器,java,unit-testing,mocking,mockito,powermock,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(Sys

通过查看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"));
            }
        }
    }
}
但当我调试测试用例时,checkSecurityList allowedClasses方法中的SecurityManager secMan为null

我做错了什么?请帮我把这个修好

提前感谢

您必须将BaseUtils.class添加到@PrepareForTest,而不是像@PrepareForTestBaseUtils.class那样的System.class


您可以在中找到更多信息,并解释为什么应该这样做,您可能会发现JUnit 4.12、PowerMock 1.7.0和Mockito 2.7的测试通过了。19@glitch您的系统可能有一个安全管理器。我在一个没有设置安全管理器的系统中运行它。BaseUtils中的方法就是我正在测试的方法,所以为什么您要求模拟已测试的类。如果它被模拟,我们测试的是一个被模拟的对象,而不是实际的实现,我不会要求你模拟这个类@PrepareForTest注释并不意味着类被模拟,它意味着类的字节码被修改以启用某些功能。这种特性之一是能够调用模拟系统类。我提供了链接,您可以在其中找到更详细的信息。