gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 13:45:47 28 4
gpt4 key购买 nike

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

最佳答案

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

假设您有一个具有私有(private)或 protected 字段访问权限的 Entity 类,并且没有提供 setter 方法

@Entity
public class MyEntity {

@Id
private Long id;

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

在您的测试类中,由于缺少 setter 方法,您无法设置 entityid

使用 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

但请尝试阅读 docs .

关于java - 在 Junit 测试中使用 ReflectionTestUtils.setField(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44667573/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com