Cannot mock Security manager using powermokito

2019-08-16 00:44发布

问题:

By looking at the answer written by Lauri in Mockito mock of SecurityManager throwing an exception I wrote a unit test by mocking the Security manager. Below is the test case

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

    }
}

and this is testing the static method below

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

But when I debug the test case the SecurityManager secMan is null in checkSecurity(List<String> allowedClasses) method.

What I am doing wrong? Please help me to fix this.

Thanks in advance

回答1:

You have to add BaseUtils.class to @PrepareForTest not a System.class, like @PrepareForTest(BaseUtils.class)

More information you may find in documentation and explanation why it should be done in such way you may find here