如何使用Mockito或PowerMock来设置类中的私有字段。

huangapple 未分类评论51阅读模式
标题翻译

how to use Mockito or PowerMock to set a private field in a class

问题

我有以下代码:

@RunWith(PowerMockRunner.class)
public NeedToTestClass () {
    private String needToSetValueField;

    ......

    public String needToTestMethod() {
        return "the field value is " + this.needToSetValueField;
    } 
}

在我尝试测试该方法时,是否有办法设置(或模拟)needToSetValueField?请帮忙。谢谢。

英文翻译

I have a following code

@RunWith(PowerMockRunner.class)
public NeedToTestClass () {
     private String needToSetValueField;

     ......

     public String needToTestMethod() {
           return "the field value is " + this.needToSetValueField;
     } 
}

Is there anyway I can set(or mock) the needToSetValueField when I try to test the method? Please help. Thanks.

答案1

得分: 0

@Taschi 应该获得荣誉。可以使用简单的反射来设置类中的私有变量。在单元测试中,可以使用 spy 注解模拟 NeedToTestClass 类,然后使用反射来设置私有变量 needToSetValueField。谢谢。

英文翻译

@Taschi should get the credit. A simple reflection can be used to set a private variable in the class. What can be done in unit test is to mock the class NeedToTestClass using spy annotation and then use reflection to set the private variable needToSetValueField. Thanks.

huangapple
  • 本文由 发表于 2020年5月31日 02:20:10
  • 转载请务必保留本文链接:https://java.coder-hub.com/62106876.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定