Programmaticaly将属性值分配给@Parameters

时间:2016-12-04 05:36:52

标签: java junit properties-file

我的属性文件如下所示:

demo6312623.mockable.io/testingmoke = 200;aaaa
www.google.com = 200;bbbb

我需要迭代文件中的所有属性并传递如下参数:

Object[][] data = new Object[][] {
    { 200, "demo6312623.mockable.io/testing", "aaaa"}, 
    { 200, "www.google.com", "bbbb"}
} 

我可以像这样迭代属性文件:

for (Map.Entry<Object, Object> props : props.entrySet()) {
    System.out.println((String)props.getKey() +" nnnnn "+ (String)props.getValue());        
 }

但我不确定如何将这些参数传递给此方法:

@Parameters
public static Collection < Object[] > addedNumbers() throws IOException {
    props = new Properties();
    FileInputStream fin = new FileInputStream("src/test/resources/application.properties");
    props.load(fin);

    for (Map.Entry < Object, Object > props: props.entrySet()) {
        System.out.println((String) props.getKey() + " nnnnn " + (String) props.getValue());
    }

    // not sure how to assign the values to the 2 dimensional array by  splitting from ";"
    //      Object[][] data = new Object[][]{
    //          { 200, "demo6312623.mockable.io/testing", "aaaa"}, 
    //          { 200, "www.google.com", "bbbb"}
    //      };
    return Arrays.asList(data);
}

1 个答案:

答案 0 :(得分:1)

您需要从Collection方法返回ArrayList类型(例如@Parameters),这样您就可以使用内嵌注释设置如下代码所示的数据:

@Parameters
public static Collection<Object[]> testData() throws Exception {

   //Load the properties file from src/test/resources
   FileInputStream fin = new FileInputStream("src/test/resources/
                                         application.properties");
   Properties props = new Properties();
   props.load(fin);

   //Create ArrayList object
   List<Object[]> testDataList = new ArrayList<>();

   String key = null;
   String[] value = null;
   String[] testData = null;
   for (Map.Entry<Object, Object> property : props.entrySet()) {
         key = (String)property.getKey();//Get the key

         //Split the property value with ';' and assign to String array
         String[] value = ((String)property.getValue()).split(";");
         testData[0] = value[0];
         testData[1]= value[1];

         //add to arraylist
         testDataList.add(testData);
    }

    // return arraylist object
    return testDataList;
 }
相关问题