Junit 测试中 ReflectionTestUtils.setField() 的使用

新手上路,请多包涵

我是 JUnittesting 的新手,所以我有一个问题。谁能告诉我为什么我们在 Junit 测试中使用 ReflectionTestUtils.setField() 示例。

原文由 user5459039 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 2.6k
1 个回答

如评论中所述,java 文档很好地解释了用法。但我也想给你一个简单的例子。

假设您有一个具有私有或受保护字段访问权限 且未提供 setter 方法 的实体类。

 @Entity
public class MyEntity {

   @Id
   private Long id;

   public Long getId(Long id){
       this.id = id;
   }
}

在您的测试类中,您无法设置 identity 因为缺少 setter 方法。

使用 ReflectionTestUtils.setField 您可以出于测试目的这样做:

 ReflectionTestUtils.setField(myEntity, "id", 1);

参数说明:

 public static void setField(Object targetObject,
                            String name,
                            Object value)
Set the field with the given name on the provided targetObject to the supplied value.
This method delegates to setField(Object, String, Object, Class), supplying null for the type argument.

Parameters:
targetObject - the target object on which to set the field; never null
name - the name of the field to set; never null
value - the value to set

但试一试并阅读 文档

原文由 Patrick 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题