java – Mockito模拟SecurityManager抛出异常

我正在尝试模拟SecurityManager类.当我运行以下代码时,Mockito会抛出异常:

@After
public void tearDown()
{
    SecurityManager securityManagerMock = mock(SecurityManager.class);
    System.setSecurityManager(securityManagerMock);
}

堆栈跟踪是无限重复的以下行:

at org.mockito.internal.creation.MethodInterceptorFilter.intercept(MethodInterceptorFilter.java:42)
at $java.lang.SecurityManager$$EnhancerByMockitoWithCGLIB$$3ceafc0f.checkMemberAccess(<generated>)
at java.lang.Class.checkMemberAccess(Class.java:2157)
at java.lang.Class.getDeclaredField(Class.java:1879)
at org.mockito.internal.creation.cglib.CGLIBHacker.reflectOnCreateInfo(CGLIBHacker.java:44)
at org.mockito.internal.creation.cglib.CGLIBHacker.setMockitoNamingPolicy(CGLIBHacker.java:20)
at org.mockito.internal.creation.MethodInterceptorFilter.intercept(MethodInterceptorFilter.java:42)
at $java.lang.SecurityManager$$EnhancerByMockitoWithCGLIB$$3ceafc0f.checkMemberAccess(<generated>)
at java.lang.Class.checkMemberAccess(Class.java:2157)
at java.lang.Class.getDeclaredField(Class.java:1879)
at org.mockito.internal.creation.cglib.CGLIBHacker.reflectOnCreateInfo(CGLIBHacker.java:44)
at org.mockito.internal.creation.cglib.CGLIBHacker.setMockitoNamingPolicy(CGLIBHacker.java:20)
at org.mockito.internal.creation.MethodInterceptorFilter.intercept(MethodInterceptorFilter.java:42)
at $java.lang.SecurityManager$$EnhancerByMockitoWithCGLIB$$3ceafc0f.checkMemberAccess(<generated>)
at java.lang.Class.checkMemberAccess(Class.java:2157)
at java.lang.Class.getDeclaredField(Class.java:1879)
at org.mockito.internal.creation.cglib.CGLIBHacker.reflectOnCreateInfo(CGLIBHacker.java:44)
at org.mockito.internal.creation.cglib.CGLIBHacker.setMockitoNamingPolicy(CGLIBHacker.java:20)

我在这做错了什么?

解决方法:

PS!您还可以模拟对getSecurityManager()方法的静态方法调用.

模拟静态方法
请参阅http://code.google.com/p/powermock/wiki/MockitoUsage的maunal

在课程级别添加@PrepareForTest.

@PrepareForTest(System.class); // System.class contains static methods

调用PowerMockito.mockStatic()来模拟静态类(使用PowerMockito.mockStaticPartial(类,方法)来模拟特定方法):

PowerMockito.mockStatic(System.class);

只需使用Mockito.when()来设置您的期望:

Mockito.when(System.getSecurityManager()).thenReturn(securityManagerMock);
上一篇:java – Mockito:等待与参数匹配的调用


下一篇:java – Mockito NullPointerException