单元测试使用powermock的静态方法

时间:2013-09-04 11:56:19

标签: java unit-testing 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写这个?

2 个答案:

答案 0 :(得分:4)

此解决方案还使用Easymock来设定期望值。 首先,您需要为testclass做准备:

@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);

答案 1 :(得分:1)

// 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);    
相关问题