具有动态测试次数的JUnit测试 [英] JUnit test with dynamic number of tests
问题描述
在我们的项目中,我有几个 JUnit 测试,例如从目录中获取每个文件并对其运行测试。如果我在 TestCase
中实现 testEveryFileInDirectory
方法,则只显示一个可能失败或成功的测试。但我对每个文件的结果感兴趣。如何编写 TestCase
/ TestSuite
,以便每个文件显示为单独的测试,例如:在Eclipse的图形化TestRunner中? (为每个文件编写显式测试方法不是一种选择。)
In our project I have several JUnit tests that e.g. take every file from a directory and run a test on it. If I implement a testEveryFileInDirectory
method in the TestCase
this shows up as only one test that may fail or succeed. But I am interested in the results on each individual file. How can I write a TestCase
/ TestSuite
such that each file shows up as a separate test e.g. in the graphical TestRunner of Eclipse? (Coding an explicit test method for each file is not an option.)
还要比较问题在Eclipse Testrunner中使用名称的ParameterizedTest 。
推荐答案
在JUnit 4中查看参数化测试。
Take a look at Parameterized Tests in JUnit 4.
实际上我几天前就这样做了。我将尝试解释...
Actually I did this a few days ago. I'll try to explain ...
首先正常构建您的测试类,就像您只使用一个输入文件进行测试一样。
用以下内容装饰你的课程:
First build your test class normally, as you where just testing with one input file. Decorate your class with:
@RunWith(Parameterized.class)
构建一个构造函数,该构造函数接受将在每次测试调用中更改的输入(在这种情况下,它可能是文件本身)
Build one constructor that takes the input that will change in every test call (in this case it may be the file itself)
然后,构建一个静态方法,它将返回一个 Collection
的数组。集合中的每个数组都将包含类构造函数的输入参数,例如文件。用以下方法装饰此方法:
Then, build a static method that will return a Collection
of arrays. Each array in the collection will contain the input arguments for your class constructor e.g. the file. Decorate this method with:
@Parameters
这是一个示例类。
@RunWith(Parameterized.class)
public class ParameterizedTest {
private File file;
public ParameterizedTest(File file) {
this.file = file;
}
@Test
public void test1() throws Exception { }
@Test
public void test2() throws Exception { }
@Parameters
public static Collection<Object[]> data() {
// load the files as you want
Object[] fileArg1 = new Object[] { new File("path1") };
Object[] fileArg2 = new Object[] { new File("path2") };
Collection<Object[]> data = new ArrayList<Object[]>();
data.add(fileArg1);
data.add(fileArg2);
return data;
}
}
同时检查这个示例
这篇关于具有动态测试次数的JUnit测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!