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