All of us write various automation tests for the application that we test in our every day work. One thing that has been debated the most is the use of soft assertions. Before we dive deep into the debate, a quick look at the two types of assertions.

Hard Assertions (or simply Assertions)

Tests immediately fail and stop executing the moment a failure occurs in the assertion. You may want to use a hard assert if you want to verify if you have logged in correctly and fail the test if you haven’t as there is no point in proceeding further if the test if the pre-condition itself fails.

Soft Assertions

Tests don’t stop running even if an assertion condition fails, but the test itself is marked as a failed test to indicate the right result. This is useful if you are doing multiple validations in a form (well.. you may actually question why you should be doing multiple validations in the first place which is probably a separate topic by itself), you may actually want to complete all the validations and fail the test once all validations are complete in case of failures.

Now.. there are multiple ways of doing soft asserts. You can write your own custom logic using the regular assert, but trap any exceptions and make the test proceed further. Or, you can use the TestNG library (for Java) which does this magic for you.

Here is how you initialize the TestNG assertions…

https://gist.github.com/rameshbaskar/1f0df0e227c42a94aeb5

Here is a sample test for a Hard Assertion…

https://gist.github.com/rameshbaskar/7fa17bb7b61e8e883b62

Here is a sample test for Soft Assertion which does not fail the test…

https://gist.github.com/rameshbaskar/21652650cc38eca0c8ce

And here is a soft assertion that actually marks the test as a failure…

https://gist.github.com/rameshbaskar/f938828d87f0e1cd386b

If you look at the above test, the softAssert.assertAll() does the trick. This method collates all the failures and decides whether to fail the test or not at the end. So instead of writing a custom logic, the TestNG library itself offers the facility to perform Soft Assertions in your test.