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"));
}
}
}
}
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.
Thanks in advance