问题描述
通过在 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模拟安全管理器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!