标题翻译
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.
专注分享java语言的经验与见解,让所有开发者获益!
评论