使用PowerMock模拟私有字段和私有方法

要模拟的类:

public class PrivateObject {

    private String privateString;

    public PrivateObject(String privateString) {
 this.privateString = privateString;
    }

    private String getPrivateString() {
 return this.privateString;
    }

}

使用PowerMock模拟:

// 类实例(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");

你可能感兴趣的:(unit-test)