Assert in Selenium

Assert is to compare the expected with actual.

Assert.assertEquals:
If fails i.e if expected != actual, then test execution stops with exception: java.lang.AssertionError
Else, Program continues normal flow after checking the Assert statement.

Assert.assertTrue:
is to evaluate a condition

Usage:
Best example is login, if logged then continue else stop executing rest of the test case.
To check if a table exist or not, if not present, then no need to loop through the content..

Let's see the implementation of Assert.


Assert.assertEquals statement:
package testPkg;

import org.testng.Assert;
import org.testng.annotations.Test;

public class AssertVerify {

 /*@Test
 public static void fn_Assert() {*/
 public static void main(String[] args){
  System.out.println("Start");
  Assert.assertEquals((3*2), 4);//Exception:java.lang.AssertionError
  System.out.println("End"); //This statement will not execute, and excution stops here
 }
}
OutPut:
Start
Exception in thread "main" java.lang.AssertionError: expected [4] but found [6]
 at org.testng.Assert.fail(Assert.java:94)
 at org.testng.Assert.failNotEquals(Assert.java:494)
 at org.testng.Assert.assertEquals(Assert.java:123)
To avoid skipping the rest of code if Assert fails, then catch the exception and fail the testcase, then continue to the next test case (mostly in framework)
Let's look into a +ve scenario, where Assert passes....
package testPkg;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.Test;

public class AssertVerify {

 /*@Test
 public static void fn_Assert() {*/
 public static void main(String[] args){
                System.out.println("Start Testcase");
  WebDriver driver = new FirefoxDriver();
  driver.get("http:\\www.qavalidation.com");
  System.out.println("Launched browser with URL");
  Assert.assertEquals(driver.getTitle(), "QA Validation");
                System.out.println("Launched browser with URL");
  driver.close();
  System.out.println("Browser closed");
 }
}
OutPut:
Start Testcase
Launched browser with URL
Browser closed

Assert.assertTrue
public static void main(String[] args) {
 System.out.println("start");
 Assert.assertTrue((5*2)>12, "5*2 is not greater than 12");
 System.out.println("end");
 }
OutPut:
start
Exception in thread "main" java.lang.AssertionError: 5*2 is not greater than 12 expected [true] but found [false]
 at org.testng.Assert.fail(Assert.java:94)
 at org.testng.Assert.failNotEquals(Assert.java:494)

No comments:

Post a Comment