依赖
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
<version>2.0.9</version>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>2.0.9</version>
</dependency>
示例代码
public class StaticUtils {
public static String getPublicStatic() {
return "publicStatic";
}
}
public class MyService {
@Resource
InnerService innerService;
public String getPublic() {
return innerService.getPublicInner();
}
public String getStatic() {
return StaticUtils.getPublicStatic();
}
public String getPrivate() {
return privateMethod();
}
private String privateMethod() {
return "private";
}
public Entity getEntity() {
return new Entity("serviceEntity");
}
public void noArgs(){
noArgPublic();
System.out.println("noArgs");
}
public void noArgPublic() {
System.out.println("noArgPublic");
}
}
@RunWith(PowerMockRunner.class)
@PrepareForTest({StaticUtils.class})// 静态方法需要准备
public class MyServiceTest {
//完整使用测试类时使用该注解,需要部分修改使用spy,需要完全mock就使用mock
@InjectMocks
MyService myService;
// @Mock(name = "service") 内部属性使用名称注入简便方法
@Mock
InnerService innerService;
@Before
public void setUp() throws Exception {
// Whitebox.setInternalState(myService,"service",innerService); //内部属性使用名称注入
PowerMockito.mockStatic(StaticUtils.class);//静态方法需要准备
}
//当前使用junit4 org.junit.Test;
//使用junit5的注解会导致识别失败,报 No tests found matching Method 的错误
@Test
//mock注入类的public方法
public void testPublic() {
PowerMockito.when(innerService.getPublicInner()).thenReturn("mockPublic");
System.out.println(myService.getPublic());
PowerMockito.when(StaticUtils.getPublicStatic()).thenReturn("mockStatic");
System.out.println(myService.getStatic());
}
@Test
//mock私有方法
public void testPrivate() throws Exception {
MyService myServiceSpy = PowerMockito.spy(myService);//获取spy对象,当想mock测试类方法时可使用
PowerMockito.doReturn("mockPrivate").when(myServiceSpy,"privateMethod");
System.out.println(myServiceSpy.getPrivate());
}
@Test
//mock构造方法
public void testConstructor() throws Exception {
Entity mockEntity = new Entity("mockEntity");
PowerMockito.whenNew(Entity.class).withArguments(Mockito.anyString()).thenReturn(mockEntity);
System.out.println(myService.getEntity().getName());
}
@Test
public void testNoArgs(){
MyService myServiceSpy = PowerMockito.spy(myService);
Mockito.doNothing().when(myServiceSpy).noArgPublic();
myServiceSpy.noArgs();
}
}
注意事项
当前使用junit4 org.junit.Test;使用junit5的注解会导致识别失败,报 No tests found matching Method 的错误
使用jacoco时覆盖率不准确,maven日志报a different version of class was executed at runtime ;
for report generation the same class files must be used as at runtime
是因为在@PrepareForTest加了当前测试类