To tackle the disadvantage of Hard Assertions where we want to continue the execution even if some assert fails and see the result at the end of the test.
Soft Assertions are the type of assertions that do not throw an exception when an assertion fails and continue with the next step after assert statement. This is in the case where our test requires multiple assertions to be executed and we want all of the assertions to be executed first before marking (failing/skipping) the tests.
Consider these 2 examples:
1) We're verifying many CSS values of the same element like background-color, font-family, and color in a single test case.
element.getAttribute("background-color")
element.getCssValue("font-family")
element.getCssValue("color")
Obviously, if any one of these fails we would like to catch it and mark the test case as fail but that doesn't mean if background-color verification fails it should mark the test case fail without even checking the other 2 CSS values. In this case, we want our test to verify all and then share the final status as failed even if any one of these isn't working.
2) We're verifying that all the links present on the page are working fine or not.
Here too, if anyone of the links isn't working we would like to catch it and mark the test case as fail but that doesn't mean if one link verification fails it should mark the test case fail without even checking the other links. In this case, we want our test to verify all the links and then share the final status as fail even if any one of these isn't working.
In case we use normal asserts like Assert.assertTrue() or Assert.assertEquals() in TestNG, @Test Method will immediately fail after any of the Asserts fails.
So here, SoftAssertion helps to collect all the assertions throughout the @Test method and to see assertions result at the end of the test, we have to invoke assertAll().
Sample code:
@Test
public void testSA() {
SoftAssert softAssert = new SoftAssert();
softAssert.assertEquals("powderblue", elementBGColor, "The background color isn't matching.");
softAssert.assertTrue("lato,sans-serif".equals(elementFF), "Font-family appears to be different.");
softAssert.assertTrue("#222".equals(elementColor), "Element color appears to be different.");
softAssert.assertAll();
}
Comments
Post a Comment