unit testing static methods using powermock

2019-06-10 07:33发布

问题:

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