2017-09-27 28 views
0

通過查看LauriMockito 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)方法。

我做錯了什麼?請幫我解決這個問題。

在此先感謝

+0

您的測試通過JUnit 4.12,PowerMock 1.7.0和Mockito 2.7.19 – glytching

+0

@ glitch它可能是您的系統有安全管理器。我在沒有設置安全管理器的系統中運行它。 –

回答

1

您必須添加BaseUtils.class@PrepareForTest不是System.class,像@PrepareForTest(BaseUtils.class)

的更多信息,你可以在documentation和解釋發現它爲什麼要以這樣的方式來完成,你可能會發現here

+0

「BaseUtils」中的方法是我測試的方法,所以你爲什麼要模擬已經過測試的類。如果它嘲笑我們正在測試一個嘲弄的對象而不是實際的實現 –

+0

我並不是要你嘲笑這個課程。 '@ PrepareForTest'註解並不意味着類被嘲笑,這意味着該類的字節碼被修改以啓用某些功能。其中一個特點是可以調用模擬系統類。我提供了鏈接,您可以在其中找到更詳細的信息。 –