Assertions In Selenium Using Junit And TestNG Frameworks

By Sruthy

By Sruthy

Sruthy, with her 10+ years of experience, is a dynamic professional who seamlessly blends her creative soul with technical prowess. With a Technical Degree in Graphics Design and Communications and a Bachelor’s Degree in Electronics and Communication, she brings a unique combination of artistic flair…

Learn about our editorial policies.
Updated March 7, 2024

This Selenium Tutorial on Assertions Explains What Are Assertions in Selenium And Different Types of Assertions And Assertion Methods Using Junit and TestNG Frameworks:

Assertions are used for validating a test case and helps us understand if a test case has passed or failed. The assertion is considered to be met if the actual result of an application matches with that of the expected result.

While automating web applications using Selenium, we need to validate our tests to verify if they are working as expected or not (that is, if a test case result is pass/fails).

=> Take A Look At The Selenium Beginners Guide Here.

A test case is considered to be passed only if all the assertions have been met. Assertions in Selenium can be handled by pre-defined methods of Junit and TestNG frameworks, which will be explained in detail in this article.

Assertions in Selenium

Assertions In Selenium

Assertions are used to perform various kinds of validations in the test cases, which in turn helps us to decide whether the test case has passed or failed. We consider a test as successful if it runs without any exception.

Video Tutorial On Assertions

Types of Assertions in Selenium

There are two types of assertions in Selenium and the categorization depends on how the assertion behaves after a condition is pass or fail.

Here, we would discuss two types of  assertions in Selenium:

  • Hard Assertions
  • Soft Assertions

Click here for sample test cases for testing assertions.

#1) Hard Assertions (Or Simply Assertions)

A hard assertion does not continue with execution until the assertion condition is met.

Hard assertions usually throw an Assertion Error whenever an assertion condition has not been met. The test case will be immediately marked as Failed when a hard assertion condition fails.

A scenario to use this kind of assertion is that, when you want to verify if you have logged in correctly and fail the test if you haven’t made a successful login, as there is no point in proceeding further if the pre-condition(login) itself fails.

Let us take another example illustrated here :

Consider a test case to assert the title of a webpage.

public class LearnAssertions {
	
WebDriver driver;

//Store current project workspace location in a string variable ‘path’
String path = System.getProperty("user.dir”);
	
@BeforeTest
public void SetDriver(){

//Mention the location of ChromeDriver in localsystem
System.setProperty("webdriver.chrome.driver",path+"\\Drivers\\chromedriver.exe");
driver = new ChromeDriver();// Object is created- Chrome browser is opened
driver.manage().window().maximize();

}

@Test
public void verifyTitle()
{
driver.get(https://www.amazon.com);
String ActualTitle = driver.getTitle();
String ExpectedTitle = “Amazon.com: Online Shopping for Electronics, Apparel,
    Computers, Books, DVDs & more”;
Assert.assertEquals(ActualTitle, ExpectedTitle);
System.out.println(“Assert passed”);
}

@AfterTest
public void closedriver(){

//closes the browser instance
driver.close();

}

Hard Assertions

In the example, the ‘ActualTitle’ variable will hold the title text from automation. ‘ExpectedTitle’ holds the expected string data. Assert.assertEquals() verifies if both the text are equal. The above test case will pass and continue to the next line of execution since the Actual text and Expected text are the same.

Console :
Assert passed.
PASSED: VerifyTitle

Hard Assertions Result 1

The same test case when failed will throw an exception and halt the execution at that instance.

Now, let us change the Expected Title to the wrong one.

public class LearnAssertions {
	
WebDriver driver;

//Store current project workspace location in a string variable ‘path’
String path = System.getProperty("user.dir"); 
	
@BeforeTest
public void SetDriver(){

//Mention the location of chromeDriver in localsystem
System.setProperty("webdriver.chrome.driver",path+"\\Drivers\\chromedriver.exe");
driver = new ChromeDriver();// Object is created- Chrome browser is opened
driver.manage().window().maximize();

}

@Test
public void verifyTitle()
{
driver.get(https://www.amazon.com);
String ActualTitle = driver.getTitle();
String ExpectedTitle = “Welcome to Amazon”;
Assert.assertEquals(ActualTitle, ExpectedTitle);
System.out.println(“Assert passed”);

}

@AfterTest
public void closedriver(){

//closes the browser instance
driver.close();

}

Console:

java.lang.AssertionError: expected [Welcome to Amazon] but found [Amazon.com: Online Shopping for Electronics, Apparel, Computers, Books, DVDs & more]

Hard Assertions Result 2

From the console, we can see that the print statement was skipped(System.out.println) since failure was encountered in the Assert statement and it threw an exception.

#2) Soft Assertions

A soft assertion continues with the next step of the test execution even if the assertion condition is not met.

Soft Assertions are the type of assertions that do not throw an exception automatically when an assertion fails unless it is asked for. This is useful if you are doing multiple validations in a form, out of which only a few validations directly have an impact on deciding the test case status.

Here, we use a class called SoftAssert and the method assertAll() is called to throw all exceptions caught during execution. When softAssert is used, it performs assertion and if an exception is found, its not thrown immediately, rather it continues until we call the method assertAll() to throw all exceptions caught.

It is wise to use different objects of ‘SoftAssert’ class for each test case.

Consider the test case to assert the title of the page

In the below example, two objects of ‘SoftAssert’ class are created to be used in two different test cases.

public class LearnAssertionsSoft {
WebDriver driver;
	
//Object of Class SoftAssert is created to use its methods
SoftAssert softassert = new SoftAssert();
SoftAssert softassert2 = new SoftAssert();
	
//current project workspace
String path = System.getProperty("user.dir"); 
	
@BeforeTest
public void SetDriver(){
System.setProperty("webdriver.chrome.driver",path+"\\Drivers\\chromedriver.exe");
	
driver = new ChromeDriver();// Object is created - Chrome browser is opened
driver.manage().window().maximize();
}
	
//Soft Assertion example - with a failure test case example
@Test
public void verifyTitle(){
driver.get("https://amazon.in");
String ActualTitle = driver.getTitle();
System.out.println("Actual Title :"+ActualTitle);
String ExpectedTitle = "cameras, books, watches, apparel, shoes and e-Gift 
Cards. Free Shipping & Cash on Delivery Available.";
		
//Soft assert applied to verify title
softassert.assertEquals(ActualTitle, ExpectedTitle);


//If failed, this line gets printed and execution is not halted
System.out.println("Assertion 1 is executed”);

softassert.assertAll();

}

//Soft Assertion example - with a positive flow test case example
@Test
public void verifyElement(){
WebElement AmazonIcon = 
driver.findElement(By.Xpath(“//div[contains(@id,’amazon_icon’)]);
softassert2.assertEquals (true, AmazonIcon.isDisplayed());
softassert2.assertAll();
System.out.println("Icon is displayed");
System.out.println("Assertion 2 is executed”);

}
	
	
@AfterTest
public void closedriver(){
driver.close();
//Checks for failures if any and throws them at the end of execution 
}
	
}

Console:

Actual Title: Amazon.com: Online Shopping for Electronics, Apparel, Computers, Books, DVDs & more
Assertion 1 is executed
Icon is displayed
Assertion 2 is executed

Soft Assertions Result 1

java.lang.AssertionError: The following asserts failed:

expected [Welcome to Amazon] but found [Amazon.com: Online Shopping for Electronics, Apparel, Computers, Books, DVDs & more]

Soft Assertions Result 2

From the console, we can understand that even though the assertion was a failure in the first test case (verifyTitle), the execution continued to the next line wherein the statement – ‘Assertion 1 is executed’ was printed and only after softAssert was called, the exception was thrown.

When To Use Hard And Soft Assertion?

If you need to execute all the steps of a test case to be executed even after an assertion fails, and you also want to report assertion exception, then opt for using Soft Assertions. Using Soft Assertions in your test scripts is a good practice and an effective way of handling your test execution

If you want your test case execution to proceed only after an assertion is passed (For Example, To Verify valid login and only then execute the other steps), then use Hard Assertions.

Junit Assert Methods

The various types of Junit Assert methods are explained below in detail.

#1) assertEquals

assertequals method compares the expected result with that of the actual result. It throws an AssertionError if the expected result does not match with that of the actual result and terminates the program execution at assert equals method.

Syntax:

public static void assertEquals(String expected, String actual)

Example:

String expected = “https://www.google.com”;

String actualURL= “https://www.google.com”;

Assert.assertEquals(expected, actualURL);

#2) assertTrue

asserttrue method asserts that a specified condition is true.

It takes in two parameters i.e. one is the message and the other is the condition against which the assertion needs to be applied. It throws an AssertionError if the condition passed to the asserttrue method is not satisfied.

Syntax:

public static void assertTrue(java.lang.String message, boolean condition)

message – Message to be displayed in case of an Assertion Error.
condition – Condition against which the assertion needs to be applied.

Example:

Assert.assertTrue(“Assert True test message”, true);

#3) assertFalse

assert false method asserts that a specified condition is false.

It takes in two parameters, i.e. one is the message and the other is the condition against which the assertion needs to be applied. It throws an AssertionError if the condition passed to the assertfalse method is not satisfied.

Syntax:

public static void assertFalse(java.lang.String message, boolean condition)

message – Message to be displayed in case of an Assertion Error.
condition – Condition against which the assertion needs to be applied.

Example:

Assert.assertFalse(“Assert false test message” false);

#4) assertNull

assert null is used to verify if the provided object contains a null value. It takes an object as the parameter and throws an AssertionError if the provided object does not hold a null value.

Syntax:

public static void assertNull(Object object)

Example:

DemoClass demo = new DemoClass();
Assert.assertNull(demo);

#5) assertNotNull

assert not null is used to verify that a provided object does not hold a null value. It takes an object as the parameter and throws an AssertionError if the provided object does not contain a null value.

Syntax:

public static void assertNotNull(Object object)

Example:

DemoClass demo = new DemoClass();
Assert.assertNotNull(demo);

#6) assertSame

assert same method checks if two objects provided as parameters refer to the same object. It throws an AssertionError if the provided objects do not refer to the same object with the message provided.

Please note that Assert same compares the references of objects only, but not the actual values.

Syntax:

public static void assertSame(String message, Object expected,Object actual)

Example:

DemoClass1 demo1 = new DemoClass1();
DemoClass2 demo2= new DemoClass2();
Assert.assertSame(“Two objects are equal”, demo1, demo2);

#7) assertNotSame

assert not same verifies that two objects are not equal. If two objects to refer to the same object, then an AssertionError will be thrown.

Please note that the assert not same method compares the references of objects and not the values present in the objects.

Syntax:

public static void assertNotSame(String message, Object expected, Object actual)

Example:

DemoClass1 demo1 = new DemoClass1();
DemoClass2 demo2= new DemoClass2();
Assert.assertNotSame(“Two objects are not equal”, demo1, demo2);

#8) assertArrayEquals

assert equals verifies that two object arrays are equal. If both the arrays hold null values, then they are being considered as equal. This method throws an AssertionError with the message provided if both the object arrays are not considered equal.

Syntax:

public static void assertArrayEquals(String message, Object[] expected, Object[] actual)

message – Message to be displayed in case of an assertion error.
expected – Array of objects.
actual – Array of objects.

Example:

String[] expected = {“Mango”,”Apple”,”Banana”}

String[] actual = {“ Mango”,”Apple”,”Banana”}

Assert.assertArrayEquals(expected,actual);

TestNG Assert Methods

TestNG Assert methods will be the same as the Junit assertion methods that are discussed above. The major difference between Junit and TestNG assertion methods come in the way of handling assertions.

TestNG provides more advanced assertion handling techniques such as dependent classes, Group tests, Parameterized tests, etc.

Video Tutorials On TestNG Assert Methods

Part I


Part II


Part III

#1) assertEquals

This method is used to assert if two data values are equal. We can compare the values of different data types like string, boolean, integer. etc. Whenever the expected and actual values are the same, then the assertion passes with no exception. If they are not, then an AssertionError is thrown.

Usage: This kind of assertion is used to verify the case when the data displayed on the webpage is as expected or as per the requirement specified.

Syntax:

Assert.assertEquals(actual,expected)

Parameters:

Actual – The actual value that we expect from automation.
Expected –The expected value.

Example: To verify that, if Amazon home page has a title saying,  ‘Amazon.com: Online Shopping for Electronics, Apparel, Computers, Books, DVDs & more’

@Test
public void verifyTitle()
{
WebDriver driver = new FirefoxDriver();
driver.get(https://www.amazon.com);
String ActualTitle = driver.getTitle();
String ExpectedTitle = “Amazon.com: Online Shopping for Electronics, Apparel, 
    Computers, Books, DVDs & more”;
Assert.assertEquals(ActualTitle, ExpectedTitle);
System.out.println(“Assert passed”);
}
 

Console :

Assert passed.
PASSED: VerifyTitle

In the above example, two strings were verified for equal values. Likewise, equality of other data types like integer, boolean, etc. can be verified.

#2) assertNotEquals

assertNotEquals is used to verify if two data values are not equal. It is just the opposite of the functioning of assertEquals Assertion. Whenever the expected and actual values match, the assertion fails with an exception and marks the test-case as “failed”.

Usage: This is used in cases when we would like to verify that each data is unique on a web page. For Example, a telephone directory, where no 2 phone numbers are the same.

Syntax:

Assert.assertNotEquals(actual,expected)

Parameters:

Actual – The actual value that we expect from automation.
Expected – The expected value.

Example: To verify that the pin codes of two different areas are unique/not same.

@Test // test case to verify AssertNotEquals
 
public void verifyAssertNotEquals{
WebDriver driver = new FirefoxDriver();
driver.get("http://chennaiiq.com/chennai/pincode-by-name.php");
WebElement Adambakkam = 
driver.findElement(By.xpath("//table[contains(@class,'TBox')]/tbody/tr[5]/td[3]"));
WebElement Aminijikarai = 
driver.findElement(By.xpath("//table[contains(@class,'TBox')]/tbody/tr[15]/td[3]"));
	  
String Pincode1 = Adambakkam.getText();
String Pincode2 = Aminijikarai.getText();
	  
System.out.println("Two Unique pincodes are :  " +Pincode1 +"  &&  "+Pincode2);
	  
Assert.assertNotEquals(Pincode1, Pincode2);
System.out.println(“Assert passed”);
 
}

Console :

Two Unique pincodes are : 600012 && 600001 

Assert passed.
PASSED: verifyAssertNotEqual

#3) assertTrue

assertTrue is used to verify if a given Boolean condition is true. This assertion returns true if the specified condition passes, if not, then an assertion error is thrown.

Syntax:

Assert.assertTrue(BooleanCondition);

Parameters:
BooleanCondition – Condition to check for its return type to be True.

Usage:

Example: To verify, if the SignIn button is present on the homepage of Amazon.in (assert for the display of the button).

Assert.assertTrue(SignIn.isDisplayed());

Here, it verifies if the Boolean condition – SignIn.IsDisplayed() returns TRUE.

Example: To verify if a button is present on the webpage.

@Test // Test cases for AssertTrue
public void verifyAssertTrue(){
WebDriver driver = new FirefoxDriver();
driver.get("https://www.amazon.in");// Open browser and pass URL in address 
bar
WebElement Navigation = 
driver.findElement(By.xpath("//*[@id='nav-link-yourAccount']"));
WebElement SignInButton = driver.findElement(By.xpath("//span[text()='Sign
 in']"));
Actions move = new Actions(driver);
move.moveToElement(Navigation).build().perform();
	 
Boolean checkButtonPresence = SignInButton.isDisplayed();
	  
Assert.assertTrue(checkButtonPresence);
	
System.out.println("Button is displayed");
}

Console :

Button is displayed 
PASSED: verifyAssertTrue

#4) assertFalse

assertFalse is used to verify if a given Boolean condition is false. In other words, the return type of the given Boolean condition should be False. This assertion passes if the specified condition has a FALSE return type if not, an assertion error is thrown.

Syntax:

Assert.assertFlase(BooleanCondition);

Parameters:
BooleanCondition – Condition to check for its return type to be False.

Usage: A scenario where it can be used is to verify if an element is not present on a webpage after a certain action.

Example 1: Sign-in Button should not be displayed after login.

Assert.assertFalse(SignIn.isDisplayed());

This asserts if the Boolean condition – SignIn.IsDisplayed() returns FALSE.

Example 2:

 To verify if a div disappears after a particular action. So, here we verify that the div is not displayed, or in other words, Assert for a false condition on a div displayed.

@Test // Test case for AssertFalse
public void verifyAssertFalse() throws InterruptedException {
WebDriver driver = new FirefoxDriver();
driver.get("https://www.irctc.co.in");
	  
WebElement CaptchaDiv = 
driver.findElement(By.xpath("//div[contains(@id,'ImgContainer')]"));
WebElement CheckBox = driver.findElement(By.xpath("//*[@id='otpId']"));
	  
CheckBox.click();
Assert.assertFalse(CaptchaDiv.isDisplayed());
System.out.println("Captcha div dimmed out of screen");
}

Console :

Captcha div dimmed out of the screen 
PASSED: verifyAssertFalse

#5) assertNull

This assertion is used to verify if an object has a null return value. In other words, it checks if the result is null. When the object is Null, the assertion is passed without any exception.

Syntax:

AssertNull(Object)

Parameters:
Object – Any data value which holds a null value.

Usage:

Example 1:

Assert if a string is null.

@Test 
public void verifyAssertion () throws InterruptedException {
WebDriver driver = new FirefoxDriver();
driver.get("https://www.irctc.co.in");
	  
String str1 = null;
String str2 = "hello";              
AssertNull(str1); // asserts if str1 holds null value
System.out.println("String holds null value – Assert passed");
}

Example 2:

Assert if the driver value is null before initiating the chrome driver.

@Test 
public void verifyAssertion () throws InterruptedException {
WebDriver driver;
AssertNull(driver); 
System.out.println("Driver is null – Assert passed");
}

Here, the driver object is null since it’s not initiated. Hence, AssertNull(driver) will be a success as it verified if the object ‘driver’ holds a null value

#6) assertNotNull

This assertion expects a valid return type, other than the Null value. In other words, it checks for an object if it is not Null. The return type can be Boolean, string, integer, list, etc. When the object is not null, Assertion is passed, if not, an AssertionError is thrown.

Syntax:

AssertNotNull(Object)

Parameters:
Object – Any data value which holds any data value.

Usage:

Example 1: Assert is a string holds some data. That is, it is not Null.

@Test 
public void verifyAssertion () throws InterruptedException {
WebDriver driver = new FirefoxDriver();
driver.get("https://www.irctc.co.in");
	  
String str1 = null;
String str2 = "hello";              
AssertNotNull(str2); // asserts if str2 holds some value
System.out.println("String holds null value – Assert passed");
}

Example 2: Verify driver object is not null, after initiating the FirefoxDriver.

@Test 
public void verifyAssertion () throws InterruptedException {
WebDriver driver;
WebDriver driver = new FirefoxDriver();
AssertNotNull(driver); 
System.out.println("Driver is null – Assert passed");
}

Here, the driver object is initiated to firefox driver and hence ‘driver’ object holds some value since it’s not initiated. Hence, AssertNotNull (driver) will be a success as it verified if the object ‘driver’ doesn’t hold a null value

Click here for sample test cases.

Sample Programs for Assertions

Assert Equals:

package Demo;
import org.junit.Assert;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class AssertionDemo {
public static void main(String[] args) throws InterruptedException{
String sValue = "Assert Equals Test";
Assert.assertEquals("Assert Equals Test", sValue);
System.out.println("Test Passed");
}
}

Code Explanation:

The above code demonstrates the use of AssertEquals method in simple terms.

  • As discussed earlier, assert equals takes in two parameters i.e. expected result and actual result. If the expected result does not match with that of the actual result, then an assertion error will be thrown and the program execution will terminate at assert equals method.
  • The above code compares the user-defined string value to the expected string value.
  • Please note that in real time, the actual result will be a user defined operation for which the value will be fetched at run time and passed as a parameter to the assert equals method.

Assert True:

package Demo;
import org.junit.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class AssertionsDemo1 {
public static void main(String[] args) throws InterruptedException{
String expectedTitle = "Google";
System.setProperty("webdriver.gecko.driver","D:\\Data_Personal\\Demo\\geckodriver-v0.23.0-win64\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.com");
Assert.assertTrue("Title does not match", expectedTitle.equals(driver.getTitle()));
driver.close();
}
}

Code Explanation:

The above code demonstrates the usage of the assertTrue method.

  • We are initially passing the expected page title onto a variable. We are then instantiating an object of firefox driver and navigating it to the web page – https://www.google.com
  • Later, Using assertsTrue method we are comparing the opened page title with that of the expected page title. If the opened page title does not match with that of the expected title, then an assertion error will be thrown and program execution will be terminated at the assertTrue method.
  • The above code will be executed successfully only when the actual page title matches with that of the expected page title.

Assert False:

package Demo;
import org.junit.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class AssertionsDemo1 {
public static void main(String[] args) throws InterruptedException{
String expectedTitle = "Google1";
System.setProperty("webdriver.gecko.driver","D:\\Data_Personal\\Demo\\geckodriver-v0.23.0-win64\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.com");
Assert.assertFalse("Title does match", expectedTitle.equals(driver.getTitle()));
driver.close();
}
}

Code Explanation:

The above code demonstrates the usage of the assertfalse method.

  • We are initially passing the expected page title onto a variable and then instantiating an object of the firefox driver and navigating to the web page – https://www.google.com
  • Later, using the assertfalse method we are comparing the opened page title with that of the expected page title. If the opened page title matches with that of the expected title, then an assertion error will be thrown and the program execution will be terminated at the assert false method.
  • The above code will be executed successfully only when the actual page title does not match with that of the expected page title.

End To End Code For Assertions

Given below is a sample end to end code for Assertions. We have used the following scenario for simplicity purposes.

Scenario:

  • Open the web page: https://www.google.com on the Firefox browser.
  • Verify if the opened page title is equivalent to that of the expected page title using the asserttrue method.
  • On the search textbox, enter the search keyword: Selenium.
  • Hit the Enter button on the keyboard.
  • Verify if the opened page title on the search results page is equivalent to that of the expected page title using the assertequals method and assertfalse method.
  • Close the browser.

Sample Code:

packageDemo;

import org.junit.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class AssertionsDemo {
public static void main(String args[]) throws InterruptedException
{
String expectedTitle = "Google";
String expectedText = "selenium - Google Search";
System.setProperty("webdriver.gecko.driver","D:\\Data_Personal\\Demo\\geckodriver-v0.23.0-win64\\geckodriver.exe");
// Open the web page https://www.google.com using firefox browser
WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.com");

// Validate if actual web page title matches with that of expected title using assert true method
System.out.println("Assert true method validation");
Assert.assertTrue("Title does not match", expectedTitle.equals(driver.getTitle()));

// Enter the keyword selenium on the search textbox
WebElementsearchBox = driver.findElement(By.xpath("//*[@name='q']"));
searchBox.sendKeys("selenium");
searchBox.sendKeys(Keys.ENTER);
Thread.sleep(8000);

// Validate the actual page title with expected page title using assert equals method
System.out.println("Assert equals method validation");
Assert.assertEquals(expectedText, driver.getTitle());

// Page title validation using assert false method
System.out.println("Assert false method validation");
Assert.assertFalse("Title does match", expectedTitle.equals(driver.getTitle()));

// Close the current browser
driver.close();
}
}

Code output:

Initially, the Firefox browser window will be opened with the web page: https://www.google.com. Asserttrue method will verify if the opened page title matches with that of the expected page title – Google.

Google Home Page

The script will enter the search keyword as Selenium and hit the enter button.

Search on Google

Assertfalse and assertequals methods compare if the actual page title of the search results screen matches with that of the expected title – ‘selenium – Google Search’. The browser will then be closed through driver.close method.

Assertions Demo

Console Output:

The text given below will be the console output on Eclipse IDE

Console Output

Avoid common mistakes while using Assert Class

1. Suppose your project have JUnit, TestNG and python libraries configured

2. But in your script, you are using TestNG annotation and by mistake, you choose Junit Assertion, then your Assert class will be deprecated. Refer below screenshot

 Junit Assertion

Assert class will be deprecated

3. So it is very important to choose proper Assert Class, for TestNg choose the only org.TestNG Assert class

4. For Junit choose org.junit.Assert class and so on.

5. To perform Soft Assertion we need to call assertAll() method compulsorily

6. When an assertion fails it will throw assertion error not the exception

Conclusion

We can conclude this article on Assertions in Selenium with the below pointers:

  • An assertion is used to compare the actual result of an application with the expected result.
  • A test case is considered to be passed only if all the assertions have been met.
  • AssertEquals method compares the expected result with that of the actual result. It throws an AssertionError if the expected result does not match with that of the actual result and terminates the program execution at the assertequals method.
  • AssertTrue method asserts that a specified condition is true. It throws an AssertionError if the condition passed to the asserttrue method is not satisfied.
  • AssertFalse method asserts that a specified condition is false. It throws an AssertionError if the condition passed to assert false method is not satisfied.
  • AssertEquals, AssertTrue, and AssertFalse methods are the most commonly used assertions in Selenium.

In the upcoming tutorial, we will discuss various examples used in real-time project scenarios and understand how assertions are used according to the purpose.

We hope this article enriched your knowledge on Assertions in Selenium!!

=> Read Through The Easy Selenium Training Series.

Was this helpful?

Thanks for your feedback!

Leave a Comment