【问题标题】:Cannot mock Security manager using powermokito无法使用 powermokito 模拟安全管理器
【发布时间】:2017-09-27 10:22:05
【问题描述】:

通过查看LauriMockito mock of SecurityManager throwing an exception 中写的答案,我通过模拟安全管理器编写了一个单元测试。下面是测试用例

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

但是当我调试测试用例时,checkSecurity(List&lt;String&gt; allowedClasses) 方法中的 SecurityManager secMan 为空。

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

提前致谢

【问题讨论】:

  • 您的测试通过了 JUnit 4.12、PowerMock 1.7.0 和 Mockito 2.7.19
  • @glitch 可能是您的系统有一个安全管理器。我在未设置安全管理器的系统中运行它。

标签: java unit-testing mocking mockito powermock


【解决方案1】:

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

您可以在documentation 中找到更多信息,并解释为什么应该以这种方式完成,您可以找到here

【讨论】:

  • BaseUtils 中的方法是我正在测试的方法,所以为什么您要求模拟已测试的类。如果它是模拟的,我们正在测试一个模拟对象而不是实际的实现
  • 我不是要你嘲笑课堂。 @PrepareForTest 注解并不意味着模拟了一个类,它意味着修改了该类的字节码以启用某些功能。其中一项功能是调用模拟系统类的能力。我提供了链接,您可以在其中找到更多详细信息。
猜你喜欢
  • 2017-02-08
  • 2019-04-02
  • 2023-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多