ReflectionTestUtils.setField() 在 Junit 测试中用于设置对象列表。

huangapple go评论97阅读模式
英文:

Use of ReflectionTestUtils.setField() in Junit testing to set a List of objects

问题

  1. 在我的实现中我有
  2. ```List<recordEntity> entityList = service.mapper(parameter1,parameter2);```
  3. 我需要为这个```entityList```设置一个静态值以便进行单元测试
  4. 我知道可以使用```ReflectionTestUtils```来设置值我甚至已经在另一个场景中使用过了
  5. ```ReflectionTestUtils.setField(classObject, "implementations", Collections.singletonMap("mapper", new DTOMapper()));```
  6. 但我不确定如何设置一个```list```
英文:

in my implementation , i have

List<recordEntity> entityList = service.mapper(parameter1,parameter2);

i need to set the value for this entityList with a static value for my unit testing,
i know that using ReflectionsTestUtils we can set value, even i have used this for another scenaro,

ReflectionTestUtils.setField(classObject, "implementations", Collections.singletonMap("mapper", new DTOMapper()));

but am not sure how to set a list

答案1

得分: 0

以下是您要翻译的代码部分:

  1. 我刚刚做了一个小示例我编写了一个带有列表的类并使用反射将一个值设置到这个列表中
  2. public class ABC {
  3. public static List entityList = new ArrayList();
  4. public void method() {
  5. System.out.println(entityList);
  6. }
  7. }
  1. 并且Junit测试如下
  2. @ExtendWith(MockitoExtension.class)
  3. class ABCTest {
  4. @InjectMocks
  5. ABC abc;
  6. @Test
  7. void myTest() throws NoSuchFieldException, IllegalAccessException {
  8. List<ABC> staticEntityList = List.of(new ABC(), new ABC());
  9. // 使用反射设置entityList的值
  10. Field entityListField = ABC.class.getDeclaredField("entityList");
  11. entityListField.setAccessible(true);
  12. entityListField.set(abc, staticEntityList);
  13. abc.method();
  14. }
  15. }

因此,其大小变为 ReflectionTestUtils.setField() 在 Junit 测试中用于设置对象列表。

英文:

I just did a little example. I wrote a class with a List and using reflection set to this list a value:

  1. public class ABC {
  2. public static List entityList = new ArrayList();
  3. public void method() {
  4. System.out.println(entityList);
  5. }
  6. }

and junit test

  1. @ExtendWith(MockitoExtension.class)
  2. class ABCTest {
  3. @InjectMocks
  4. ABC abc;
  5. @Test
  6. void myTest() throws NoSuchFieldException, IllegalAccessException {
  7. List&lt;ABC&gt; staticEntityList = List.of(new ABC(), new ABC());
  8. // Using reflection to set the value of entityList
  9. Field entityListField = ABC.class.getDeclaredField(&quot;entityList&quot;);
  10. entityListField.setAccessible(true);
  11. entityListField.set(abc, staticEntityList);
  12. abc.method();
  13. }
  14. }

So size of it become to ReflectionTestUtils.setField() 在 Junit 测试中用于设置对象列表。

huangapple
  • 本文由 发表于 2023年5月30日 10:56:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76361345.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定