1

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

输入文件

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相同的行为

回答

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(); 
     } 
    } 
}