测试按列名读取的 FieldSetMapper 会抛出异常

Testing a FieldSetMapper which reads by column names throws exception

作业配置xml中的线映射逻辑如下:

<property name="lineTokenizer">
    <bean
            class="org.springframework.batch.item.file.transform.DelimitedLineTokenizer">
        <property name="names" value="ID,NAME"/>
        <property name="strict" value="false"/>
    </bean>
</property>
<property name="fieldSetMapper">
    <bean class="com.company.batch.mappers.EmpFieldSetMapper"/>
</property>

field set mapper读取逻辑如下:

fieldSet.readString("ID");

但是在为 EmpFieldSetMapper 编写 UT 时,出现以下错误:

java.lang.IllegalArgumentException: Cannot access columns by name without meta data

    at org.springframework.batch.item.file.transform.DefaultFieldSet.indexOf(DefaultFieldSet.java:675)
    at org.springframework.batch.item.file.transform.DefaultFieldSet.readString(DefaultFieldSet.java:169)

UT如下:

@Before
public void setUp() throws Exception {
    mapper = new EmpFieldSetMapper();
    DefaultFieldSetFactory fieldSetFactory = new DefaultFieldSetFactory();

    String[] inputValues = { "123", "RAJ" };
    fieldSet = fieldSetFactory.create(inputValues);
}

@Test
public void testMapFieldSet() {
    try {
        Model model = mapper.mapFieldSet(fieldSet);
        assertEquals("ID field mapping is wrong", "123", model.getId());
        assertEquals("NAME field mapping is wrong", "RAJ", model.getName());
    } catch (BindException e) {
        fail("Exception during field set mapping");
    }
}

我想我需要将 DefaultFieldSetMapper 更改为其他内容但不确定。这个问题可以通过用索引替换列名来解决,但我想保留 EmpFieldSetMapper 中的列名。所以需要建议。

我找到了答案。还需要传入列名。

String[] inputValues = { "123", "RAJ" };
String[] inputColumns = { "ID", "NAME" };
fieldSet = fieldSetFactory.create(inputValues, inputColumns);