使用powermock对静态方法进行unit testing

我想为我的项目中的一些静态方法编写unit testing用例,

我的class级代码片段,

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()编写unit testing用例。 我如何使用powermock写这个?

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

此解决方案还使用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); 

调用要测试的方法,然后使用以下方法validation模拟:

 PowerMock.verify(Util.class);