Mockito模拟SecurityManager抛出异常

时间:2012-02-19 06:51:17

标签: java junit mockito

我正在试图模仿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)

我在这里做错了什么?

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:0)

更改SecurityManager时,应在测试后将其重置为原始SecurityManager。

您可以使用System Rules库进行测试。使用此规则设置和重置安全管理器只需两行代码。

@Rule
public ProvideSecurityManager provideSecurityManager
  = new ProvideSecurityManager(yourSecurityManager);

在测试中使用yourSecurityManager,在测试之外使用原始安全管理器。