循环填充JUnit参数?

时间:2014-06-16 19:45:07

标签: java arrays junit junit4 nested-loops

我正在尝试从数组列表中提取单个URL,并让它们充当一系列JUnit测试的参数。但是,到目前为止,我一直无法这样做。

该项目侧重于Web测试,我使用的方法检索给定URL的HTTP状态代码。

以下代码是JUnit Test的参数部分。它接受URL和预期值作为输入,并将它们与实际值进行比较,以确定每个值是否通过。

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


        Object[][] data = new Object[][]{{"http://google.com",200}, {"http://yahoo.com", 404}};


        return Arrays.asList(data);
    }

有没有人有通过参数化JUnit测试循环遍历列表数组的经验?例)

Object [][] data = new Object [][]{{urlArray.get(0), statusArray.get(0},....{urlArray.get(i), statusArray.get(i)}}

感谢您提供任何帮助!

以下完整代码:

import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.junit.Before; 
import org.junit.Assert;
import org.junit.runner.RunWith; 
import org.junit.runners.Parameterized; 
import org.junit.runners.Parameterized.Parameters;



@RunWith(Parameterized.class)

public class CodeFinderTest extends CodeFinder {

private String url; 
private int expected; 


public CodeFinderTest(String url, int expected){
    this.url = url; 
    this.expected = expected; 

}


CodeFinder instance;
    @Before
    public void setup(){
        instance = new CodeFinder(); 
}


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


        Object[][] data = new Object[][]{{"http://google.com",200}, {"http://yahoo.com", 404}};


        return Arrays.asList(data);
    }

    @Test
    public void testFinder() throws IOException{
        Assert.assertEquals(expected, instance.status(url)); 
    }

}

1 个答案:

答案 0 :(得分:1)

提供测试数据的方法是一种真正的方法。因此你可以这样做:

@Parameters
public static Collection<Object[]> testData(){
  List<Object[]> data = new ArrayList<>();
  Iterator<String> itUrl = urlArray.iterator();
  Iterator<Integer> itStatus = statusArray.iterator();
  while (itUrl.hasNext())
    data.add(new Object [] {itUrl.next(), itStatus.next()});
  return data;
}