通過查看Lauri
在Mockito mock of SecurityManager throwing an exception中編寫的答案,我編寫了一個模擬安全管理器的單元測試。下面是測試案例無法模擬使用powermokito的安全管理器
@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);
}
}
,這是測試下方
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"));
}
}
}
}
靜態方法但當我調試測試情況下,安全管理器secMan
是空的checkSecurity(List<String> allowedClasses)
方法。
我做錯了什麼?請幫我解決這個問題。
在此先感謝
您的測試通過JUnit 4.12,PowerMock 1.7.0和Mockito 2.7.19 – glytching
@ glitch它可能是您的系統有安全管理器。我在沒有設置安全管理器的系統中運行它。 –