问题描述
我正在为我的(小型)程序编写单元测试,并且在大约30个不同的文件中指定了测试用例.
为了测试它,我需要做的是遍历所有文件,解析它们并执行所需内容的循环.
I'm writing unit tests for my (small) program, and the test cases are specified in around 30 different files.
To test it, all I need is a loop that goes over all the files, parse them, and execute what's needed.
问题在于,在这种情况下,我的所有测试都将被视为一个,因为所有测试均使用@Test
表示法在同一函数中.
是否可以以某种方式拆分它,而不必为每个测试文件都具有单独的功能?
The problem is that in that case, all of my tests will be considered as one, since it's all in the same function with the @Test
notation.
Is it possible to split it somehow without having to have a separate function for each test file?
将所有测试作为一个测试用例的问题在于,我看不到哪个测试用例未能通过该过程.如果其中一个失败,则其余的失败(我将使1个测试失败,而不是5/30失败)
The problem with all the tests as one test case, is that I can't see which test case fail the process; and if one fails it fail the rest (I'll get 1 test failed instead of 5/30 failed)
我目前正在使用JUnit(4.12),但我没有义务继续使用它,因此,如果有更好的解决方案,我可以切换框架.
I'm currently using JUnit (4.12), but I'm not obligated to keep using it, so I can switch framework if there's a better solution.
谢谢!
示例:
public class MyTests {
@Test
public void testFromFiles {
// loop through all the files
}
}
output: 1 test run successfully
更新:选定的答案对我来说非常有效,我还为JUnit 5(而不是4)添加了另一个解决方案,以防它对某人有所帮助.
Update: The selected answer worked great for me, and I added another solution with JUnit 5 (instead of 4), in case it will help someone.
推荐答案
尝试这种方式:
@RunWith(Parameterized.class)
public class EdiTest {
@SuppressWarnings("WeakerAccess")
@Parameterized.Parameter(value = 0)
public String model;
@SuppressWarnings("WeakerAccess")
@Parameterized.Parameter(value = 1)
public String filename;
@Parameterized.Parameters(name = "{index}: testEDI({0}, {1})")
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][]{
{"753", "edi753_A.edi"},
{"753", "edi753_B.edi"},
{"754", "edi754.edi"},
{"810", "edi810-withTax.edi"},
{"810", "edi810-withoutTax.edi"},
});
}
@Before
public void setUpContext() throws Exception {
TestContextManager testContextManager = new TestContextManager(getClass());
testContextManager.prepareTestInstance(this);
}
@Test
public void testEDI() throws IOException {
String edi = IOUtils.toString(ClassLoader.getSystemResource(filename));
EdiConverter driver = ediConverterProvider.getConverter(model);
// your test code here
}
}
这篇关于从Java中的循环创建多个单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!