英文:
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();
}
}
英文:
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<ABC> staticEntityList = List.of(new ABC(), new ABC());
// Using reflection to set the value of entityList
Field entityListField = ABC.class.getDeclaredField("entityList");
entityListField.setAccessible(true);
entityListField.set(abc, staticEntityList);
abc.method();
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论