使用PowerMock进行单元测试
环境: jdk 1.8 junit 4
maven
<dependency>
<groupId>org.powermockgroupId>
<artifactId>powermock-module-junit4artifactId>
<version>2.0.9version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.powermockgroupId>
<artifactId>powermock-api-mockito2artifactId>
<version>2.0.9version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.mockitogroupId>
<artifactId>mockito-coreartifactId>
<version>3.7.7version>
<scope>testscope>
dependency>
处理静态方法的单元测试:
@PrepareForTest(**静态类**.class)
@RunWith(PowerMockRunner.class)
多个以,分隔
PowerMockito.mockStatic(**静态类**.class);
PowerMockito.when(T method).thenReturn(object);
PowerMockito.mockStatic(xxx.class);
//类名,方法名,参数
PowerMockito.doNothing().when(xxx.class, "方法名", anyString());
spy被测类:
TestPowerMock powerMock= PowerMockito.spy(new TestPowerMock());
构造返回:
PowerMockito.when(powerMock, "methodName", param1, param2).thenReturn(2);