1

I have this situation where I'm reading values from input file using junitparams. In some cases, my rows have values in all the columns (say 5), however, in other cases only the first few columns have values. I want junitparams to assign value for the available variables and then null or any other default value to rest of the variables, which doesn't have input values Is it possible to do it with junit params?

INPUT file

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

My code is

@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 I was using feed4junit earlier to accomplish this but due to some compatability issue between junit 4.12 and feed4junit, I have to switch to junitparams. I want to simulate the same behaviour with junit param

4

1 回答 1

2

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

@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();
        }
    }
}
于 2016-05-21T20:41:24.437 回答