我正在尝试从数组列表中提取各个 URL,并将它们作为一系列 JUnit 测试的参数。然而,到目前为止我还无法做到这一点。
这个项目专注于 Web 测试,我使用的方法检索给定 URL 的 HTTP 状态代码。
下面的代码是 JUnit 测试的参数部分。它接受 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));
}
}
最佳答案
提供测试数据的方法是真实的方法。因此你可以这样做:
@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;
}
关于java - 循环填充 JUnit 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24251047/