当前位置:   article > 正文

使用PowerMock模拟私有字段和私有方法_powermock set private field

powermock set private field

要模拟的类:

public class PrivateObject {

    private String privateString;

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

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

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

使用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");
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/274474
推荐阅读
相关标签
  

闽ICP备14008679号