如何在 TestNG 中执行软断言

How to perform a soft assertion in TestNG

下面是TestNG框架中的断言方法示例。

private static void failAssertNoEqual(String defaultMessage, String message) {
    if (message != null) {
      fail(message);
    } else {
      fail(defaultMessage);
    }
  }

这里是失败方法。

/**
   * Fails a test with the given message.
   * @param message the assertion error message
   */
  public static void fail(String message) {
    throw new AssertionError(message);
  }

所以当断言失败时,测试失败并出现断言错误。

就我而言,我必须断言报告的内容。我希望我的测试能够验证每一列并列出断言失败,而不是在第一次失败时从方法中抛出。这样,我就不必修复一个字段并重新运行测试来验证下一个字段。

我试图将每个断言放在一个 Try Catch 块中,但这使代码变得非常冗长。

   try {
            Assert.assertEquals("active", "inactive");
        }
        catch (AssertionError e) {
            //Store this somewhere
        }

否则我将不得不编写自定义函数来执行每个断言,将它们存储在一个集合中,最后根据值通过或失败测试。但是后来我并没有真正使用 TestNG。

TestNG 中是否有内置方法来执行软断言。如果没有,实现这一目标的理想方法是什么。

您可以使用SoftAssert

public class ExampleTest {

 private SoftAssert softAssert = new SoftAssert();

 @Test
 public void test() {
     softAssert.assertTrue(false);
     softAssert.assertTrue(false);
     // your assertions
     softAssert.assertAll();
 }

    @Test(expectedExceptions = IOException.class, expectedExceptionsMessageRegExp = ".* Message .*")
    public void exceptionTest() throws Exception {
        throw new IOException("IO Test");
    }

    @Test(expectedExceptions = { IOException.class, NullPointerException.class }, expectedExceptionsMessageRegExp = ".* Message .*")
    public void exceptionsTest() throws Exception {
        throw new IOException("IO Test");
    }