项目的单元测试经常会对某一些类的私有属性和私有方法进行mock,这个时候powerMock可以胜任这个任务。
maven 依赖的pom
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>1.4.10</version>
<scope>test</scope>
</dependency>
需要mock的类
public class PrivateObject {
private String privateString;
public PrivateObject(String privateString) {
this.privateString = privateString;
}
private String getPrivateString() {
return this.privateString;
}
}
具体mock的代码
// 类实例(class instance)
PrivateObject instance = new PrivateObject ();
// 模拟私有字段/变量(private field/variable)
MemberModifier.field(PrivateObject .class, "privateString")
.set(instance , "hellomock");
// 模拟私有方法(private method)
MemberModifier
.stub(MemberMatcher.method(PrivateObject .class,"getPrivateString"))
.toReturn("Power Mock");