运行 循环中的 Junit 测试,如果其中一个失败则继续进一步

Running Junit test in loop and continuing further if one in between fail

我有五个不同的测试数据和 运行 循环中的(相同的)JUnit 测试(五次)。也就是说,在每次循环迭代中,将从 JSON 个文件中读取新的测试输入数据,并且测试将是 运行,这基本上执行 AsertEquals。

我非常清楚 JUnit 参数化最适合这种情况,但暂时我不得不坚持 运行ning 测试,循环使用不同的测试数据。

我的测试基本上是这样的:

for (int i = 0; i < tests.length; i++) {
            int test = tests[i];
                       logger.info("---------------------------------------------------------------------------------------------------------------------------------------------------" +
                    "--------------------------------------------------------------------------------------------------------------------------------------------------------");
            logger.info("Executing Test: " + tests[i]);
            logger.info("Json file for Test " + tests[i] + "  is " + file);
            logger.info("---------------------------------------------------------------------------------------------------------------------------------------------------" +
                    "--------------------------------------------------------------------------------------------------------------------------------------------------------");
            FileReader fr = new FileReader(file);
            kparams = readKernelParameters.readJsonFile(fr);
            setUpMatrices();
            setUpKernel();
            setUpPSM();
            if (!setUpFailure) {
                logTestConfiguration();
                if (logPsmOutput) {
                    File testFile = getPSMFileOutput();
                    write(testFile, Matrix.transpose(velocity));
                }
                if (testsToBeRun[i] == 5) {
                    Assert.assertNotEquals("Running PSM Check " + tests[i] + ": ", 0f, (double) Matrix.diff(vOut, velocity, quality)[6], 1.0f);
//here I want to check if above Assert.assertNotEquals was successful, if yes //then I would like to write in log file
                } else {
                    Assert.assertEquals("Running PSM Check " + tests[i] + ": ", 0f, (double) Matrix.diff(vOut, velocity, quality)[6], 1.0f);
//same here
                }
            } else {
                Log.error("Failure in test setup");
                Assert.fail("Failure in test setup");
            }
        }

现在我有以下问题:

1) 如何检查 Assert.asserEquals 和 Assert.assertNotEquals 是否成功?因为它们 return void 我不能在 if 条件下写它们。有没有其他方法可以检查它?

2) 目前,发生的情况是,如果一项测试失败,例如测试 -2,然后它不会 运行 进一步循环并退出。而我想进一步迭代并 运行 进一步测试。

我知道我的 for 循环对于这种情况可能不太好,但我想知道我是否可以用它实现我想要的。

你只需要 try-catch:

String failureMsg = "";
for (int i = 0; i < tests.length; i++) {
    try {
      // your test logic comes here
    } catch (AssertionError assertFaild) {
      // log error or signal it somehow, e.g.:
      failureMsg = failureMsg + assertFaild.getMessage();
    }
}
if (!failureMsg.isEmpty()) {
     // you might want to collect more data
     Assert.fail(failureMsg);
}