我正在尝试模拟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()方法的静态方法调用。
模拟静态方法参见maunalhttp://code.google.com/p/powermock/wiki/MockitoUsage
在类级别添加@PrepareForTest。
@PrepareForTest(System.class); // System.class contains static methods
调用PowerMockito.mockStatic()来模拟静态类(使用PowerMockito.mockStaticPartial(class,method)来模拟特定方法):
PowerMockito.mockStatic(System.class);
只需使用Mockito.when()设置您的期望值:
Mockito.when(System.getSecurityManager()).thenReturn(securityManagerMock);
更改SecurityManager时,应在测试后将其重置为原始SecurityManager。
您可以使用系统规则库进行测试。使用此规则,设置和重置安全管理器只是两行代码。
@Rule
public ProvideSecurityManager provideSecurityManager
= new ProvideSecurityManager(yourSecurityManager);
在测试中使用SecurityManager,在测试之外使用原始安全管理器。