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

2022-09-02 12:16:49

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


答案 1

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

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

@Entity
public class MyEntity {

   @Id
   private Long id;

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

在测试类中,由于缺少 setter 方法,因此无法设置 a。identity

使用,您可以将其用于测试目的: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

但是试一试并阅读文档


答案 2

另一个用例:

我们外部化了许多属性,例如:URL的,端点和应用程序属性中的许多其他属性,如下所示:

kf.get.profile.endpoint=/profile
kf.get.clients.endpoint=clients

然后在如下应用中使用它:

  @Value("${kf.get.clients.endpoint}")
  private String getClientEndpoint

每当我们编写单元测试时,我们都会得到NullPointerException,因为Spring不能像@Autowired那样注入@value。(至少目前,我不知道其他选择。因此,为了避免我们可以使用ReflectreTestUtils来注入外部化的属性。如下图所示:

ReflectionTestUtils.setField(targetObject,"getClientEndpoint","lorem");

推荐