Introducing assertions

Testing in Selenium is incomplete if we don't have a way to verify our test results. The TestNG framework provides the Assert class, using which we can do validations and verifications in TestNG. We can use assertions to verify text on screen, do validations, and so on.

The most common methods in the Assert class are given here:

  • assertTrue(condition, message): Takes two arguments, which are condition and message. A check is done to see whether the Condition is true or not. If the Condition is evaluated as false, then it fails and the message gets printed. The message is optional.
  • assertFalse(condition, message): Takes two arguments, which are condition and messageA check is done to see whether the Condition is false or not. If the Condition is evaluated as true, then it fails and the message gets printed. The message is optional. 
  • assertNull(object, message): Checks whether an object is null. If the object is not null, then it fails and the optional message is printed.
  • assertNotNull(object, message): Checks whether an object is not null. If the object is null, then it fails and the optional message is printed.
  • assertEquals(actual,expected,message): Checks whether the actual and expected are equal. If these are not equal, then it fails and the optional message is printed.
  • assertNotEquals(actual, expected, message)Checks whether the actual and expected are not equal. If these are equal, then it fails and the optional message is printed.

The following code is a simple example using assertions:

@Listeners(org.packt.listeners.SampleListener1.class)
public class ListenerClass {
@Test
public void checkListeners() {
System.setProperty("webdriver.chrome.driver",
System.getProperty("user.dir")
+ "\src\main\resources\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://www.freecrm.com");
System.out.println("Title is : " + driver.getTitle());
Assert.assertEquals(driver.getTitle(),
"#1 Free CRM software in the cloud for sales and service");
}
}

Once this test is run after right-clicking on project and selecting Run As TestNG Test, the script navigates to the freecrm website and passes when it finds the correct title.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.230.82