Use Of Hard Assertion In Selenium

Posted By : Manish Kumar | 28-Mar-2018

As we need to check both positive and negative test cases in the script and check for the test cases is passed or failed, but the system should continue running our code to the end and logs all test case results, for this, we use Assertions in Selenium.

 
What is Assertion: Assertion is used to decide that a given test case is passed as per expected outcome or is deviating from the expected. A test case or code can only be said as successful if it executes and does not throw an exception.
 
Assertions can be classified into two categories: Hard Assert and Soft Assert
 
Let's discuss Hard Assert.
 
Hard Assertion:  A hard assert is used when we need to abort the specific test case if a condition fails and it is desired that system should move to next test case. Some of the examples for the Hard assert can be listed as below with their syntax

 

assertEquals : Assert.assertEquals(actual,expected); assertTrue : Assert.assertTrue(condition); assertNotEquals: Assert.assertNotEquals(actual,expected,Message); assertFalse : Assert.assertFalse(condition); assertNull: Assert.assertNull(object); assertNotNull: Assert.assertNotNull(object);

 
 
Lets have a look on the examples for both cases where test case is passed and where test case marked as failed 
<>
@Test
	public void testCaseVerifyHomePage() {
		driver= new FirefoxDriver();
		driver.navigate().to("www.google.com");
               System.out.println("Assertion case started");
		Assert.assertEquals("Google", driver.getTitle());
                 System.out.println("Assertion case finished"); 
	}
<>
In this case both the lines will be displayed as the test case is going to be passed and the output will be:

 

Assertion case started Assertion case finished

 

But if the assertion test is failed:

<>
@Test
	public void testCaseVerifyHomePage() {
		driver= new FirefoxDriver();
		driver.navigate().to("www.google.com");
               System.out.println("Assertion case started");
		Assert.assertEquals("Ggooggllee", driver.getTitle());
                 System.out.println("Assertion case finished"); 
	}
</>
In this case, the only 1st line will be shown in output as test case will be aborted as soon as assertion fails. 

 

Assertion case started

 
Hope, this will clarify how to use Hard Assertion in the selenium. 

 

 

 

 

 

Related Tags

About Author

Author Image
Manish Kumar

Manish is Adaptive and passionate to learn new technical skills, have knowledge of testing and love to play badminton in free time

Request for Proposal

Name is required

Comment is required

Sending message..