Home > Software engineering >  How to print failed assertions only without stack trace in soft assertAll() in Selenium?
How to print failed assertions only without stack trace in soft assertAll() in Selenium?

Time:10-20

Is there any way of printing just failed assertions without the entire stack trace when Selenium executes assertAll method?

SoftAssert sa = new SoftAssert();
sa.assertTrue(true,"A failed");
sa.assertTrue(false,"B failed");
sa.assertAll();

So, say this snippet has two assertions either returns true and false. So assertAll() method returns as below.

java.lang.AssertionError: The following asserts failed:
    B failed expected [true] but found [false]
    at org.testng.asserts.SoftAssert.assertAll(SoftAssert.java:43)
    at testPlayGround.TestNGExperimental.verifyWEBCFGPermissions(TestNGExperimental.java:220)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:124)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:583)
        .
        .
        .
        .
        .
        .
        .
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:84)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1208)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1137)
    at org.testng.TestNG.runSuites(TestNG.java:1049)
    at org.testng.TestNG.run(TestNG.java:1017)
    at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:115)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)


===============================================
    Default test
    Tests run: 1, Failures: 1, Skips: 0
===============================================

What I want to see in the console log is like.

java.lang.AssertionError: The following asserts failed:
    B failed expected [true] but found [false]


===============================================
    Default test
    Tests run: 1, Failures: 1, Skips: 0
===============================================

Thank you in advance.

CodePudding user response:

You can use getMessage() method to print detail message instead of entire stack trace.

Code:

try {
    SoftAssert sa = new SoftAssert();
    sa.assertTrue(true, "A failed");
    sa.assertTrue(false, "B failed");
    sa.assertAll();
} catch (java.lang.AssertionError e) {
    System.out.println(e.getMessage());
}

Output:

The following asserts failed:
    B failed expected [true] but found [false]
  • Related