JUnit测试中使用ReflectionTestUtils.setField()设置对象List
用ReflectionTestUtils设置List类型字段值的方法
其实和你之前设置Map的逻辑完全一致,只是把传入的值换成List实例即可,具体步骤如下:
1. 构造测试用的List数据
先创建包含测试实体的List,可选多种实现方式:
// 方式1:可变ArrayList,可灵活添加多个实体 List<recordEntity> mockEntityList = new ArrayList<>(); mockEntityList.add(new recordEntity("参数1", "参数2")); // 替换成你的实体构造参数 mockEntityList.add(new recordEntity("参数3", "参数4")); // 方式2:Java 9+ 不可变List,适合固定测试数据 List<recordEntity> mockEntityList = List.of( new recordEntity("参数1", "参数2"), new recordEntity("参数3", "参数4") ); // 方式3:单元素不可变List,适合仅需单个测试实体的场景 List<recordEntity> mockEntityList = Collections.singletonList(new recordEntity("参数1", "参数2"));
2. 用ReflectionTestUtils设置字段
直接调用setField方法,第三个参数传入构造好的List即可:
ReflectionTestUtils.setField(classObject, "entityList", mockEntityList);
注意事项
- 确保
"entityList"是目标类中成员变量的准确名称(反射对大小写敏感) - 不管字段是private还是protected,ReflectionTestUtils都能直接访问修改
补充:如果entityList是局部变量的情况
如果你的entityList是方法内的局部变量(就像你代码里写的List<recordEntity> entityList = service.mapper(...)),ReflectionTestUtils没法直接修改局部变量。这时候应该直接mockservice.mapper方法的返回值,比如用Mockito:
// 先mock service实例(如果还未初始化mock) Service service = mock(Service.class); // 指定mapper方法返回你构造的List when(service.mapper(any(), any())).thenReturn(mockEntityList);
内容的提问来源于stack exchange,提问作者F0cus
相关产品推荐
相关产品推荐

