我想在数据是外部的情况下执行JUnit参数化测试。我有一个对象列表,只需要知道如何将其转换为对象数组的集合。我看到下面的堆栈溢出问题,但我想从从我的方法读取的文件中添加数据。
使用非基元参数的参数化 JUnit 测试?
工作代码:像这样:
@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());
}
}
我使用了字段注入,因为它需要的代码比构造函数注入少。将名称设置为受测对象可打印更有用的输出。请查看参数化运行器的文档。
如果您不喜欢公共字段,可以使用构造函数注入。
@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());
}
}
我建议你尽可能使用TestNG。它的工作方式与 JUnit 相同,但您可以使用内部或外部数据提供程序,按给定顺序执行方法......使用起来更方便
//This method will provide data to any test method that declares that its Data Provider
//is named "test1"
@DataProvider(name = "test1")
public Object[][] createData1() {
return new Object[][] {
{ "Cedric", new Integer(36) },
{ "Anne", new Integer(37)},
};
}
//This test method declares that its data should be supplied by the Data Provider
//named "test1"
@Test(dataProvider = "test1")
public void verifyData1(String n1, Integer n2) {
System.out.println(n1 + " " + n2);
}
我让它这样做:
List<BranchMailChildSample> items = tool.unmarshallExcel(BranchMailChildSample.class);
Collection<Object[]> data = new ArrayList<Object[]>();
for(BranchMailChildSample item : items)
{
Object[] objItem = new Object[] { item };
data.add(objItem);
}
return data;
实际上,如果您使用 JUnit 4.12 和理论运行器,这样的事情应该可以工作:
@RunWith(Theories.class)
public class MyTest
{
@DataPoints public static List<MyClass> myFunctionThatReturnsTestData()
{
// TODO
}
@Theory
public void canDoTheThing(MyClass m) throws Exception {