如何使用 junitparams 获得灵活的列

how to get flexible columns with junitparams

我有这种情况,我正在使用 junitparams 从输入文件中读取值。在某些情况下,我的行在所有列中都有值(比如 5),但是在其他情况下,只有前几列有值。 我希望 junitparams 为可用变量赋值,然后为没有输入值的其余变量赋值 null 或任何其他默认值 是否可以使用 junit 参数来实现?

输入文件

col1,col2,col3,col4,col5 
1,2,3,4,5
1,3,4 
1,3,4,5
1,2,3

我的密码是

@RunWith(JUnitParamsRunner.class)
public class PersonTest {

    @Test
    @FileParameters(value="src\junitParams\test.csv", mapper = CsvWithHeaderMapper.class)
    public void loadParamsFromFileWithIdentityMapper(int col1, int col2, int col3, int col4, int col5) {
        System.out.println("col1 " + col1 + " col2 " + col2 + " col3 " + col3 + " col " + col4 + " col5 " + col5);
        assertTrue(col1 > 0);
    }

}

PS 我之前使用 feed4junit 来完成这个,但是由于 junit 4.12 和 feed4junit 之间的一些兼容性问题,我不得不切换到 junitparams。我想用 junit param

模拟相同的行为

我建议提供您自己的映射器,它将一些默认数值附加到不完整的行:

@RunWith(JUnitParamsRunner.class)
public class PersonTest {

    @Test
    @FileParameters(value = "src\junitParams\test.csv", mapper = MyMapper.class)
    public void loadParamsFromFileWithIdentityMapper(int col1, int col2, int col3, int col4, int col5) {
        System.out.println("col1 " + col1 + " col2 " + col2 + " col3 " + col3 + " col " + col4 + " col5 " + col5);
        assertTrue(col1 > 0);
    }

    public static class MyMapper extends IdentityMapper {

        @Override
        public Object[] map(Reader reader) {
            Object[] map = super.map(reader);
            List<Object> result = new LinkedList<>();
            int numberOfColumns = ((String) map[0]).split(",").length;
            for (Object lineObj : map) {
                String line = (String) lineObj;
                int numberOfValues = line.split(",").length;
                line += StringUtils.repeat(",0", numberOfColumns - numberOfValues);
                result.add(line);
            }
            return result.subList(1, result.size()).toArray();
        }
    }
}