Syntax error What is difference between Assert and Verify in Selenium?

What is difference between Assert and Verify in Selenium?



There are differences between Assert and Verify in Selenium. Both of these are used to verify if a webelement is available on the page. If the Assert fails, the test execution shall be stopped.

The moment an Assertion has not passed in a step, the test steps after that step shall be hopped. However, this can be avoided by adding a try-catch block and incorporating the Assertion within this block.

So the flow of the program execution continues if the Assertion yields a true condition. If not, the following steps after the failed step gets bypassed from the execution.

To overcome this issue, there is a concept of Soft Assertion or Verify commands. Here, if there is a failure, the test execution continues and the failure logs are captured. So the flow of the program execution continues no matter if a Verify command yields a true or a false condition.

This type of assertion is added for unimportant scenarios where we can proceed with the test even if the expected result for a step has not matched with the actual results.

Code Implementation with Assert

import org.testng.Assert;
import org.testng.Annotations.Test;
public class NewTest{
   @Test
   public void f() {
      //Assertion pass scenario
      Assert.assertTrue(2+2 == 4);
      System.out.println("Scenario 1 passed");
      //Assertion fail scenario
      Assert.fail("Scenario 2 failed with Assert");
      System.out.println("Scenario 2 failed");
   }
}

Output

Code Implementation with Verify/SoftAssert

import org.testng.Assert;
import org.testng.Annotations.Test;
import org.testng.asserts.SoftAssert;
public class NewTest{
   @Test
   public void f() {
      //instance of SoftAssert
      SoftAssert s = new SoftAssert();
      //Assertion failed
      s.fail("Scenario 1 failed with Soft Assert");
      System.out.println("Scenario 1 failed");
      //Assertion failed
      s.fail("Scenario 2 failed with Soft Assert");
      System.out.println("Scenario 2 failed");
      //collects assertion result then mark test as failed/passed
      s.assertAll()ß
   }
}

Output

Updated on: 2021-06-25T13:45:55+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements