Cannot mock Security manager using powermokito

ぃ、小莉子 提交于 2019-12-11 17:18:21

问题


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



来源:https://stackoverflow.com/questions/46445422/cannot-mock-security-manager-using-powermokito

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!