Reputation: 10244
I'm trying to mock the SecurityManager
class. When I run the following code, Mockito throws an exception:
@After
public void tearDown()
{
SecurityManager securityManagerMock = mock(SecurityManager.class);
System.setSecurityManager(securityManagerMock);
}
The stack trace is the following lines repeated indefinitely:
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)
What am I doing wrong here?
Upvotes: 2
Views: 2878
Reputation: 1899
PS! You could also mock static method call to getSecurityManager() method.
Mocking Static Method See maunal at http://code.google.com/p/powermock/wiki/MockitoUsage
Add @PrepareForTest at class level.
@PrepareForTest(System.class); // System.class contains static methods
Call PowerMockito.mockStatic() to mock a static class (use PowerMockito.mockStaticPartial(class, method) to mock a specific method):
PowerMockito.mockStatic(System.class);
Just use Mockito.when() to setup your expectation:
Mockito.when(System.getSecurityManager()).thenReturn(securityManagerMock);
Upvotes: 4
Reputation: 24520
When you change the SecurityManager, you should reset it to the original SecurityManager after the test.
You may use the System Rules library for your test. Setting and resetting the security manager are just two lines of code with this rule.
@Rule
public ProvideSecurityManager provideSecurityManager
= new ProvideSecurityManager(yourSecurityManager);
Within your test yourSecurityManager is used and outside of the test the original security manager is used.
Upvotes: 0