Instancio生成测试数据报错:Unused selectors问题求解
解决Instancio生成列表时选择器未被识别的问题
问题描述
使用Instancio生成List<MyPojo>测试数据时,所有字段配置选择器都触发错误提示:Unused selectors in generate(), set(), or supply(),使用.lenient()后自定义配置被完全忽略。
POJO类:
@Data public class MyPojo { private Integer id; private LocalDate modifiedAt; private String modifiedBy; }
原测试数据生成代码:
public List<MyPojo> dummyData() { return Instancio.ofList(MyPojo.class) .size(100) .generate(field(MyPojo::getId), gen -> gen.ints().range(1,100)) .generate(field(MyPojo::getModifiedAt), gen -> gen.temporal().localDate().past()) .generate(set(MyPojo::getModifiedBy), "static value") .create(); }
解决方案
问题根源在于:Instancio.ofList(MyPojo.class)的顶层上下文是List对象,直接使用field(MyPojo::getId)这类选择器时,Instancio会尝试在List类中查找对应字段,自然无法匹配,因此提示选择器未被使用。
需要明确指定选择器作用于列表内的MyPojo实例,有两种可行方式:
方式一:使用forEach()为列表元素配置规则
public List<MyPojo> dummyData() { return Instancio.ofList(MyPojo.class) .size(100) .forEach(MyPojo.class, spec -> spec .generate(field(MyPojo::getId), gen -> gen.ints().range(1, 100)) .generate(field(MyPojo::getModifiedAt), gen -> gen.temporal().localDate().past()) .set(field(MyPojo::getModifiedBy), "static value")) .create(); }
方式二:使用within()限定选择器作用范围
public List<MyPojo> dummyData() { return Instancio.ofList(MyPojo.class) .size(100) .generate(within(MyPojo.class).field(MyPojo::getId), gen -> gen.ints().range(1, 100)) .generate(within(MyPojo.class).field(MyPojo::getModifiedAt), gen -> gen.temporal().localDate().past()) .set(within(MyPojo.class).field(MyPojo::getModifiedBy), "static value") .create(); }
补充说明
- 原代码中使用
.generate(set(...))是错误用法,设置固定值应直接使用.set()方法,而非嵌套在.generate()中。 - 两种方式都能让Instancio正确识别字段选择器,应用自定义配置生成符合要求的测试数据。
内容的提问来源于stack exchange,提问作者Dominik
相关产品推荐
相关产品推荐

