从Java循环创建多个单元测试

ari*_*nai 1 java junit unit-testing junit4

我正在为我的(小)程序编写单元测试,测试用例在大约30个不同的文件中指定.
为了测试它,我需要的只是一个遍历所有文件的循环,解析它们并执行所需的操作.

问题是,在这种情况下,我的所有测试都将被视为一个,因为它与@Test符号的功能相同.
有可能以某种方式拆分它而不必为每个测试文件分别设置一个函数吗?

作为一个测试用例的所有测试的问题是,我无法看到哪个测试用例失败了该过程; 如果一个失败,它就会失败(我会得到1个测试失败,而不是5/30失败)

我目前正在使用JUnit(4.12),但我没有义务继续使用它,所以如果有更好的解决方案,我可以切换框架.

谢谢!

例:

public class MyTests {
    @Test
    public void testFromFiles {
        // loop through all the files
    }
}

output: 1 test run successfully 
Run Code Online (Sandbox Code Playgroud)

更新:所选答案对我来说很有用,我添加了另一个解决方案JUnit 5(而不是4),以防它可以帮助某人.

Bor*_*aze 6

试试这种方式:

@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
    }

}
Run Code Online (Sandbox Code Playgroud)