我有一个.xlsx文件,每行包含在网站上执行不同自动化测试所需的参数。 我设置它的方式是这样的:
public class X_Test {
int start = Integer.valueOf(config.Get("StartRow"));
int end = Integer.valueOf(config.Get("EndRow"));//last row on the excel
@Test
@Repeat(end) //not working because ¨end¨ is not known at compilation time.
public void main() throws Throwable
{
for(int i = start ; i < end ; i++)
{
// I need to change this loop for a Repeat(#) test.
//selenium and report code here
}
}
问题是,当我需要将每行作为单独的测试时,此代码将整个.xlsx文件作为一个测试执行。
我需要解决的问题是:
我需要多次执行相同的@test main()方法,才能在.xlsx文件中每行生成一个junit测试。
如果我将excel文件中的行数固定为重复标记中的相同#,则@ Repeat(#)有效。问题是我测试的每个excel文件都有不同的行数,所以我需要它只重复到.xlsx文件的最后一行。也许我可以实施条件测试?我怎样才能做到这一点。
答案 0 :(得分:2)
要跟进我的评论,我相信parameterized tests正是您所寻找的。简而言之,参数化测试可以针对一组测试数据运行相同的测试/断言。
问题是此代码将整个.xlsx文件作为一个测试执行 当我需要它将每一行作为一个单独的测试时。
如果是这种情况,您可以进行参数化测试,通过读取和解析.xlsx来填充参数。这是我的意思的样本:
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.Arrays;
import java.util.Collection;
@RunWith(Parameterized.class)
public class SampleTest {
@Parameterized.Parameters
public static Collection<Object[]> data() throws Exception{
//TODO: Instead of hard coding this data, read and parse your .xlsx however you see fit, and return a collection of all relevant values. These will later be passed in when constructing your test class, and then can be used in your test method
return Arrays.asList(new Object[][] {
{ 1,1,2 }, { 2,2,4 }, { 3,3,6 }, { 4,4,8 }, { 5,5,10 }
});
}
private int intOne;
private int intTwo;
private int expected;
public SampleTest(final int intOne, final int intTwo, final int expected) {
this.intOne = intOne;
this.intTwo = intTwo;
this.expected = expected;
}
@Test
public void test() {
System.out.println("Verifying that " + this.intOne + " and " + this.intTwo + " equals " + this.expected);
Assert.assertEquals(this.intOne + this.intTwo, this.expected);
}
}
运行它会产生一组5个成功的测试,以及输出:
Verifying that 1 and 1 equals 2
Verifying that 2 and 2 equals 4
Verifying that 3 and 3 equals 6
Verifying that 4 and 4 equals 8
Verifying that 5 and 5 equals 10