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

11 java junit spring

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

Pat*_*ick 20

就像评论中提到的那样,java文档很好地解释了它的用法.但我想给你一个简单的例子.

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

@Entity
public class MyEntity {

   @Id
   private Long id;

   public Long getId(Long id){
       this.id = id;
   }
}
Run Code Online (Sandbox Code Playgroud)

在您的测试类中id,entity由于缺少setter方法,您无法设置自己的测试类.

使用ReflectionTestUtils.setField您可以执行此操作以进行测试:

ReflectionTestUtils.setField(myEntity, "id", 1);
Run Code Online (Sandbox Code Playgroud)

参数描述如下:

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
Run Code Online (Sandbox Code Playgroud)

但试一试并阅读文档.


Pra*_*kam 5

另一个用例:

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

kf.get.profile.endpoint=/profile
kf.get.clients.endpoint=clients
Run Code Online (Sandbox Code Playgroud)

然后在应用程序中使用它,如下所示:

  @Value("${kf.get.clients.endpoint}")
  private String getClientEndpoint
Run Code Online (Sandbox Code Playgroud)

每当我们编写单元测试时,我们都会得到NullPointerException,因为 Spring 不能像 @Autowired 那样注入 @value。(至少目前,我不知道替代方案。)所以为了避免我们可以使用ReflectionTestUtils来注入外化属性。像下面这样:

ReflectionTestUtils.setField(targetObject,"getClientEndpoint","lorem");
Run Code Online (Sandbox Code Playgroud)