0

我想为我项目中的一些静态方法编写单元测试用例,

我的课程代码片段,

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 编写这个?

4

2 回答 2

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);
于 2013-09-04T13:21:25.403 回答
0
// 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);    
于 2013-09-04T12:31:52.837 回答