gpt4 book ai didi

java - 重复相同的测试,直到满足条件并在 Junit 中完成执行

转载 作者:行者123 更新时间:2023-11-30 02:10:52 24 4
gpt4 key购买 nike

我有一个 .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 文件的最后一行。也许我可以进行条件测试?我怎样才能做到这一点。

最佳答案

为了跟进我的评论,我相信 parameterized tests是您正在寻找的。简而言之,参数化测试可以针对一组测试数据运行相同的测试/断言。

The issue is that this code executes the whole .xlsx file as one test when I need it to take each row as an individual test.

如果是这种情况,您可以进行参数化测试,其中通过读取和解析 .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

关于java - 重复相同的测试,直到满足条件并在 Junit 中完成执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50139024/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com