簡體   English   中英

使用powermock單元測試靜態方法

[英]unit testing static methods using powermock

我想為項目中的某些靜態方法編寫單元測試用例,

我的班級代碼片段,

Class Util{
  public static String getVariableValue(String name)
  {
     if(isWindows()){
       return some string...
     }
     else{
       return some other string...
     }
  }

  public static boolean isWindows(){
    if(os is windows)
       return true;
    else
      return false; 
  }

}

基本上,當isWindows()返回'false'時,我想為getVariableValue()編寫單元測試用例。 如何使用powermock編寫此代碼?

該解決方案還使用Easymock設置期望值。 首先,您需要准備測試課程:

@RunWith(PowerMockRunner.class)
@PrepareForTest(Util.class)
public class UtilTest {}

模擬靜態類:

PowerMock.mockStaticPartial(Util.class,"isWindows");

設定期望值:

EasyMock.expect(Util.isWindows()).andReturn(false); 

重播模擬:

PowerMock.replay(Util.class);

調用要測試的方法,然后使用以下方法驗證模擬:

PowerMock.verify(Util.class);
// This is the way to tell PowerMock to mock all static methods of a
// given class
PowerMock.mockStaticPartial(Util.class,"isWindows");

expect(Util.isWindows()).andReturn(false);    

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM