无法使用powermokito模拟安全管理器 [英] Cannot mock Security manager using powermokito

查看:129
本文介绍了无法使用powermokito模拟安全管理器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过在 SecurityManager的Mockito模拟中查看由Lauri编写的答案引发异常我通过模拟安全管理器编写了一个单元测试.下面是测试用例

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

但是当我调试测试用例时,checkSecurity(List<String> allowedClasses)方法中的SecurityManager secMan为空.

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.

预先感谢

推荐答案

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

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

这篇关于无法使用powermokito模拟安全管理器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆