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

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

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

问题

在我的实现中我有

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

我需要为这个```entityList```设置一个静态值以便进行单元测试
我知道可以使用```ReflectionTestUtils```来设置值我甚至已经在另一个场景中使用过了

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

但我不确定如何设置一个```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

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

我刚刚做了一个小示例我编写了一个带有列表的类并使用反射将一个值设置到这个列表中

public class ABC {

    public static List entityList = new ArrayList();

    public void method() {
        System.out.println(entityList);
    }
}
并且Junit测试如下

@ExtendWith(MockitoExtension.class)
class ABCTest {

    @InjectMocks
    ABC abc;

    @Test
    void myTest() throws NoSuchFieldException, IllegalAccessException {
        List<ABC> staticEntityList = List.of(new ABC(), new ABC());

        // 使用反射设置entityList的值
        Field entityListField = ABC.class.getDeclaredField("entityList");
        entityListField.setAccessible(true);
        entityListField.set(abc, staticEntityList);
        abc.method();
    }
}

因此,其大小变为 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:

public class ABC {

    public static List entityList = new ArrayList();

    public void method() {
        System.out.println(entityList);
    }
}

and junit test

@ExtendWith(MockitoExtension.class)
class ABCTest {

    @InjectMocks
    ABC abc;

    @Test
    void myTest() throws NoSuchFieldException, IllegalAccessException {
        List&lt;ABC&gt; staticEntityList = List.of(new ABC(), new ABC());

// Using reflection to set the value of entityList
        Field entityListField = ABC.class.getDeclaredField(&quot;entityList&quot;);
        entityListField.setAccessible(true);
        entityListField.set(abc, staticEntityList);
        abc.method();

    }
}

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:

确定