Overview

TestNG provide wide range of assert options which helps an automation tester to validate actual and expected.

Most commonly, there are 2 types of assert in selenium, third type of assert/or way is using collection to store validation and validating at the end of scenario, similar to soft assert.

1- Hard Assert-

Which skips remaining script if Assert is failed, skipping remaining assert. Say there are 10 Assert inside a script and 2nd Assert is failed, in that case remaining assert will not be executed. To overcome these soft asserts are introduced.

Common Assert method-
1- Assert.fail(“Message”)
2- Assert.pass(“Pass”);
3- Assert.assertEquals(Expected, Actual, message)

2- Soft Assert-

Soft Assert validates all assert and at the end. it checks whether all asserts are passed or not.

//Declaration of soft assert object
SoftAssert sostassert = new SoftAssert();

sostassert.assertEquals(Actualtext1, Expectedtext1, “Message”);
sostassert.assertEquals(Actualtext2, Expectedtext2, “Message”);
sostassert.assertEquals(Actualtext3, Expectedtext3, “Message”);

Suppose if second assert fails, script will continue unlike hard assert and at the very end below command is used which validate all softassert if any of them is failed then it failed overall softassert.
s_assert.assertAll();

Custom collection assert

One more way of using assert using collections which almost works like softassert. This way of using assert is useful and effective where a lot of validation is required and validation result(output) is needed at some different test.

Create a collection object-
public static ArrayList CustomAssert = new ArrayList

Now whenever you need to validate any data, which means comparison of actual and expected and if there is any mismatch happened add that failed value in above declared collection object. and use that collection size to identify whether any failure happened during that particular flow.

Step 1-

if(driver.findelement.gettext(“XYZ”).equals(“ABC”)
{

}
else
{
CustomAssert.add(“mismatch happened”)
}

Step 2
if(driver.findelement.gettext(“XYZ”).equals(“XYZ”)
{

}
else
{
CustomAssert.add(“mismatch happened”)
}

Step 3
if(driver.findelement.gettext(“XYZ”).equals(“abc”)
{

}
else
{
CustomAssert.add(“mismatch happened”)
}

In above 3 steps, 2 asserts are failed(first and third), first and third step therefore collection CustomAssert will have 2 values filled, At the end of the test size of collection(CustomAssert ) can be counted if it is greater than zero then hard assert can be used to make validation for these particular test steps as failed.

if(CustomAssert.size()>0)
{
Assert.fail(“There are “+ CustomAssert.size()+ happened during test execution.)
}

Summary-

Using collection(above method) for validation can help us in finding out validations which happened in different classes. Using above custom Assert a tester can determine or use output of one class in other classes for different automation purposes.

Happy Automating 🙂