TestNG 结合 PowerMock
使用 PowerMock 主要是因为目前的大部分 Mock 工具还不支持 mock 静态、final、私有方法等。
官方文档:https://github.com/powermock/powermock/wiki/Getting-Started
maven依赖注意选择对应的版本!!!
https://github.com/powermock/powermock/wiki/Mockito-2-Maven
pom.xml
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<powermock.version>2.0.9</powermock.version>
</properties>
<dependencies>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.4.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-testng</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
需要在测试类上面加 @PrepareForTest({StaticClass.class})
声明要 mock 的类
此外,还需使用 @ObjectFactory
声明一个创建 testng 对象的工厂方法。
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.testng.PowerMockObjectFactory;
import org.testng.Assert;
import org.testng.IObjectFactory;
import org.testng.annotations.ObjectFactory;
import org.testng.annotations.Test;
/**
* @Author song
* @Time 2024/5/29 17:17
*/
@PrepareForTest({StaticClass.class})
public class PowermockTest {
@Test
public void testMockStatic() throws Exception {
System.out.println(StaticClass.ab());
// mock静态方法
PowerMockito.mockStatic(StaticClass.class);
// 当调用 a() 方法的时候,将方法的返回值由 "a" 修改为 "x"
Mockito.when(StaticClass.a()).thenReturn("x");
Mockito.when(StaticClass.ab()).thenCallRealMethod();
Assert.assertEquals(StaticClass.ab(), "xb");
StaticClass staticClass = PowerMockito.mock(StaticClass.class);
PowerMockito.when(staticClass.callPrivateMethod()).thenCallRealMethod();
PowerMockito.when(staticClass, "isExist").thenReturn(true);
Assert.assertTrue(staticClass.callPrivateMethod());
}
@ObjectFactory
public IObjectFactory getObjectFactory() {
return new PowerMockObjectFactory();
}
}
StaticClass 代码:
public class StaticClass {
public static String a() {
return "a";
}
public static String ab() {
return a() + "b";
}
public boolean callSystemFinalMethod(String str) {
return str.isEmpty();
}
public String callSystemStaticMethod(String str) {
return System.getProperty(str);
}
public boolean callPrivateMethod() {
return isExist();
}
private boolean isExist() {
return false;
}
}
java8 以上,需要添加 VM options:
--add-opens java.base/java.lang=ALL-UNNAMED --add-opens java.base/java.util=ALL-UNNAMED --add-opens java.base/java.nio=ALL-UNNAMED --add-opens java.base/java.io=ALL-UNNAMED --add-opens java.base/sun.nio.ch=ALL-UNNAMED