unit testing static methods using powermock

ε祈祈猫儿з 提交于 2019-12-23 04:52:45

问题


I want to write unit test case for some of the static methods in my project,

Snippet of my class code,

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; 
  }

}

Basically, i want to write unit test case for getVariableValue() when isWindows() returns 'false'. How do i write this using powermock?


回答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);    



回答2:


This solutions also uses Easymock to setup the expectation. First you need to prepare you testclass:

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

Mock the static class:

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

Setup an expectation:

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

Replay the mock:

PowerMock.replay(Util.class);

Make the call to the method you want to test and afterward verify the mock with:

PowerMock.verify(Util.class);


来源:https://stackoverflow.com/questions/18613193/unit-testing-static-methods-using-powermock

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!