【发布时间】:2020-06-09 10:55:01
【问题描述】:
我正在使用@Factory 注解来调用测试类并为此生成报告。我将使用参数 1 到 100 测试大约 100 个测试用例。有什么方法可以使用 @Factory 注释中的 .CSV 表传递所有这些不同的参数。它应该从 .CSV 读取列数据并在运行时发送该参数。
【问题讨论】:
我正在使用@Factory 注解来调用测试类并为此生成报告。我将使用参数 1 到 100 测试大约 100 个测试用例。有什么方法可以使用 @Factory 注释中的 .CSV 表传递所有这些不同的参数。它应该从 .CSV 读取列数据并在运行时发送该参数。
【问题讨论】:
这是一个完整的示例,应该可以为您分解。
为方便起见,我使用opencsv 库。
这是依赖的样子
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>4.1</version>
</dependency>
这是我的 csv 文件的内容:
name,ranking,won,lost
Undertaker,1,95,5
Hitman,2,90,10
Yokozuna,10,50,50
下面是测试类的样子:
import com.opencsv.bean.CsvBindByName;
import org.testng.Assert;
import org.testng.annotations.Test;
public class SampleTestClass {
@CsvBindByName(column = "name")
private String name;
@CsvBindByName(column = "ranking")
private int ranking;
@CsvBindByName(column = "won")
private int matchesWon;
@CsvBindByName(column = "lost")
private int matchesLost;
@Test
public void testSuperStarName() {
Assert.assertNotNull(name);
}
@Test
public void testSuperStarRanking() {
Assert.assertTrue(ranking != 0);
}
@Test
public void testMatchesWon() {
Assert.assertTrue(matchesWon > 0);
}
@Test
public void testMatchesLost() {
Assert.assertTrue(matchesLost > 0);
}
@Override
public String toString() {
return "SampleTestClass{" +
"superStarName='" + name + '\'' +
", ranking=" + ranking +
", matchesWon=" + matchesWon +
", matchesLost=" + matchesLost +
'}';
}
}
这是工厂类的样子(这是您要运行的类)
import com.opencsv.bean.CsvToBean;
import com.opencsv.bean.CsvToBeanBuilder;
import org.testng.annotations.Factory;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class TestFactoryProducerTest {
@Factory
public static Object[] produceInstances() throws IOException {
try (
BufferedReader reader = Files.newBufferedReader(Paths.get("src/test/resources/62280931.csv"));
) {
CsvToBean<SampleTestClass> csvToBean = new CsvToBeanBuilder(reader)
.withType(SampleTestClass.class)
.build();
return csvToBean.parse().toArray(new SampleTestClass[0]);
}
}
}
【讨论】: