gpt4 book ai didi

java - 将 List 转换为 Collection 以进行 JUnit 参数化测试

转载 作者:行者123 更新时间:2023-12-02 04:46:18 26 4
gpt4 key购买 nike

我想使用外部数据执行 JUnit 参数化测试。我有一个对象列表,只需要知道如何将其转换为对象数组的集合。我看到下面的堆栈溢出问题,但我想添加从我的方法读取的文件中的数据。

Parameterized JUnit tests with non-primitive parameters?

工作代码:类似这样:

@RunWith(Parameterized.class)
public class sampletest {

private BranchMailChildSample branch;

public sampletest(BranchMailChildSample branch)
{
this.branch = branch;
}

@Parameters
public static Collection<Object[]> data()
{
String excel = "C:\\Resources\\TestData\\ExcelSheets\\BranchMail\\branchmail_TestData.xlsx";
ExcelMarshallerTool tool = new ExcelMarshallerTool(excel);
List<BranchMailChildSample> items = tool.unmarshallExcel(BranchMailChildSample.class);

//RIGHT HERE I NEED HELP: Convert list to Collection<Object[]>

//return items as Collection of object arrays
}

@Test
public void test()
{
System.out.println(branch.toString());
}
}

最佳答案

您不必转换列表。

@RunWith(Parameterized.class)
public class SampleTest {

@Parameters(name = "{0}")
public static List<BranchMailChildSample> data() {
String excel = "C:\\Resources\\TestData\\ExcelSheets\\BranchMail\\branchmail_TestData.xlsx";
ExcelMarshallerTool tool = new ExcelMarshallerTool(excel);
return tool.unmarshallExcel(BranchMailChildSample.class);
}

@Parameter(0)
public BranchMailChildSample branch;

@Test
public void test() {
System.out.println(branch.toString());
}
}

我使用了字段注入(inject),因为它比构造函数注入(inject)需要更少的代码。将名称设置为测试对象会打印更有用的输出。请查看documentation of the Parameterized runner .

如果您不喜欢公共(public)字段,可以使用构造函数注入(inject)。

@RunWith(Parameterized.class)
public class SampleTest {

@Parameters(name = "{0}")
public static List<BranchMailChildSample> data() {
String excel = "C:\\Resources\\TestData\\ExcelSheets\\BranchMail\\branchmail_TestData.xlsx";
ExcelMarshallerTool tool = new ExcelMarshallerTool(excel);
return tool.unmarshallExcel(BranchMailChildSample.class);
}

private final BranchMailChildSample branch;

public SampleTest(BranchMailChildSample branch) {
this.branch = branch;
}

@Test
public void test() {
System.out.println(branch.toString());
}
}

关于java - 将 List<T> 转换为 Collection<Object[]> 以进行 JUnit 参数化测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29632227/

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