How to use assertEquals() in WebDriver using driver.getText()

When we start making some  web application, We start with some UI and Every UI has menu, Check box, Button, Combo Box , Radio button, Text Field and other element of Web Application.


But most of the time we need to verify that Text or value associated with above mentioned elements of Web Application are correct or not and for this we commonly use two function
1- getText()
2- assertEquals().

getText() helps in retrieving the Text from an element by using WebElement class.This method returns the value of  inner text attribute of Element.

So why not take a look on this how it works

package com.testng.src.com.testng;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.safari.SafariDriver;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class Verify {
WebDriver driver;
@BeforeMethod
public void launch()
{
System.setProperty("webdriver.chrome.driver", "E:\DD MISHRA\workspace\chromedriver_win_26.0.1383.0\chromedriver.exe");
driver = new ChromeDriver();
}
@Test
public void verify()throws Exception
{
driver.get("http://google.co.in");
WebElement element = driver.findElement(By.xpath("//span[text()='Google Search']"));
String strng = element.getText();
System.out.println(strng);
Assert.assertEquals("Google Search", strng);
}
}

Recommended Paid Courses to Lean Selenium and Locators:

In this script
1- I have used xpath to find the Google Search button
2- By using findElement method we could find Google Search Button
3- Once we get the element, By using getText() method we could find the text on Button
4- By using assertEquals(), we verify that Google Search Text is available on Google Search Button. If text retrieved from getText() match with the String inserted in to asserEquals() method then test is passed otherwise it is  failed.

Also Read : Mobile emulation in Google Chrome using Selenium WebDriver

Result after execution of this code

Started ChromeDriver
port=22048
version=26.0.1383.0
log=E:DD MISHRAworkspaceDataDrivenWebdriverchromedriver.log
Google Search
PASSED: verify

===============================================
Default test
Tests run: 1, Failures: 0, Skips: 0
===============================================
===============================================
Default suite
Total tests run: 1, Failures: 0, Skips: 0
===============================================

There are other assert methods that could be used to verify the text in place of assertEquals()

assertTrue(strng.contains(“Search”));
assertTrue(strng.startsWith(“Google”));
assertTrue(strng.endsWith(“Search”));

If this text pattern match then test get passed other wise test get failed.

Dwarika Dhish Mishra

My name is Dwarika Dhish Mishra, its just my name and I am trying to bring the worth of my name in to actions and wants to be the solution not the problem. I believe in spreading knowledge and happiness. More over I am fun loving person and like travelling a lot. By nature I am a tester and a solution maker. I believe in the tag line of http://ted.org “Idea worth spreading” . For the same, I have created this blog to bring more and more learning to tester fraternity through day to day learning in professional and personal life. All contents are the part of my learning and so are available for all..So please spread the contents as much as you can at your end so that it could reach to every needful people in testing fraternity. I am pretty happy that more and more people are showing interest to become the part your Abode QA blog and I think this is good sign for us all because more and more content would be before you to read and to cherish. You may write or call me at my Email id: dwarika1987@gmail.com Cell: 9999978609

You may also like...

52 Responses

  1. AutomationQA says:

    Hi Dwarika,

    I tried using assertequals in my webdriver code but I am not able to understand where can we give the statement for logs.
    It compares the values but does not return any boolean value to confirm. Please explain.

    Thanks,
    Deepali

  2. @Deepali could you please elaborate your probolem, and what kind og lgs u r comparing

    • Srinivasarao says:

      Dear Dwarika Dhish Mishra,

      I write the code using TestNG in Eclipse . TestNG syntax were showing underline or strike but it’s executing in Eclipse.I am not understand why it was happen? please help me on this issue.

      Please see the below code.

      package TestNGtests;

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

      import junit.framework.Assert;

      public class TestNGTestCase_001 {
      @Test
      public void VerifyTitle() {
      WebDriver driver = new FirefoxDriver();
      driver.get(“https://accounts.google.com/ServiceLogin?service=mail&passive=true&rm=false&continue=https://mail.google.com/mail/&ss=1&scc=1&ltmpl=default&ltmplcache=2&emr=1&osid=1#identifier”);
      String PageTitle = driver.getTitle();
      Assert.assertEquals(PageTitle, “Gmail”);

      Regards,
      Srinivasarao

  3. Savita says:

    Hi,
    I am unable to use Assert.assertEquals() function it is always showing ‘Assert’ sting as strike even I imported ‘import junit.framework.Assert;’. Is it because of jar file? if yes then can you please suggest me which jar file is required for this?

    • have you added Standalone selenium jar? if yes the you can directly write junit tests.

      So please check it carefully what is the problem. or send me the stack trace so that i could help you in resolving your problem

      Thank you!!

      • Savita says:

        Thanks for quick reply there is no problem of jar but how to write fun that give me ‘PASS’ / ‘FAIL’ status that is problem.
        Can I show you sample code?

        Savita

        • Sure you can ping me on skype any day after 9:30 on my Id dwarika.dhish.mishra

        • Tanushree Bobde says:

          If you want Pass/Fail status, you can use If-Else loop instead of AssertEquals
          For eg:
          if(“expected String”.equals(“actual string”))
          {
          System.out.println(“String matches “);
          }
          else
          {
          System.out.println(“String does not match “);
          }

  4. bibekananda says:

    how to write this assert result in excel as pass fail status?

  5. Savita says:

    Hi,
    I have one class very I want to use this where I am using Assert.assertEquals(expected.trim(), actaul.trim()); by using this method want to know whether my test case is fail or pass? In this method I am giving expected & actual string if both are same then it ‘PASS’ & if both are mismatch then my test case is fail that I want to do. Can you please help me how I can do this?

    • Why not you are using if else to print pass/fail condition. In that case you need to use some more functions like text.equals(text)

      for both text you need to extract text or result in some string, or in variable.

  6. Ajeet Maurya says:

    Hello Sir,

    How to verify the slide show images on webpage using selenium webdriver.

  7. mahesh says:

    Thnkx mate. Your blog is very help full.

  8. Anusha says:

    Hi Deepali,

    For boolean value confirm you need to give condition. But i din’t use the assertequals()
    Eg: String foo = Driver.findElement(By.xpath(“/html/body/form/table/tbody/tr/td/table/tbody/tr[2]/td/div/h4”)).getText();
    System.out.println(“foo text :: “+foo);
    if (foo.equals(“Classify Customer”)) {
    System.out.println(“yes”);
    } else {
    System.out.println(“no”);
    }

  9. Niharika says:

    Hello Sir,
    Could you please elaborate more on how to verify text on images in selenium

    Thanks,
    Niharika

  10. Taru says:

    Hi please add me on your blog..

  11. M says:

    Hi, Im new to selenium.

    What If I wanted to check every element on the page?

    Would I be right n saying I need to put all the elements in a list, do getText for all and search through one by one?

    Thanks,

    M

  12. Dev says:

    Hi

    org.testng.Assert is deprecated right ? So should we use any alternative to verify the tests? Pointers would be of great help.Thank you.

    Dev

  13. raghu says:

    In my project I need to launch the application, then I need to verify the content(Text) present on the website.my requirement is ( need to keep the original text in one excel and get the text from the site and compare the expected and actual text).please let me the know process how to automate this requirement.

  14. vamshi says:

    Hi Mistra,

    I need the code in selenium WebDriver Junit. I have a test case working on, which is related to this type of below question.

    Here is my question?

    Note: I m using other link to come into this page and test.

    In this blog you have “Recent Posts” on right side. I want to test whether that field is present in this page coming from other page which consists of recent posts in it or not. Can you please help me out of this.

    I hope you understood my question.

    thanks

  15. Sandeep says:

    Sir, i am using “assert.equals(expectedvalue, actualvalue);” statement to check some condition. My problem is that i want to store “Pass” in excel file if “assert.equals(expectedvalue, actualvalue);” is success and same way i want to store “Fail” in excel file, if “assert.equals(expectedvalue, actualvalue);” is failed. Could you please help me out. Thanks.!!

    • Use try and catch block and in case of assertion get true value in try block it will write pass in excel
      Field and if it
      Gets false then it will jump to
      Catch block
      And here in catch block keep your fail status statement for excel

  16. Ragini says:

    Hi Dwarika , i am a beginner to selenium , i have worked in java development , i tried to run this code as it is , included required jars, i dont where to locate the result and how junit works when i run this class , i am getting an error as
    Error: Main method not found in class com.testng.src.com.testng.Assert_Exp, please define the main method as:
    public static void main(String[] args)
    or a JavaFX application class must extend javafx.application.Application

    should i right it with main method ? or how does it run ?

  17. Revanth says:

    How to validate below fields of a webpage by using Selenium Webdriver TestNg
    Title
    HTTP Status Code
    Logo link title text
    Page body header (if exists).

  18. ganesh says:

    I am working with windows application.I have logged into the application by using “Sikuli”

    Query : I want to click on link with given string with “Webdriver” could you please help me on this

  19. Rajesh says:

    Hi
    can you explain how to compare two text file data using assert Equals method in selenium?
    Ex:- abc.txt contains some dta
    xyz.txt contains same data
    how to compare that two files data

  20. Shubham Chauhan says:

    Hello I have a query in selenium web driver.

    Can any one let me know about how to verify the expected result from the excel sheet, so that i do not have to make changes in the script again & again, only I have to change the test data for the expected result which is dynamic in nature?

  21. khuabu says:

    HI,
    I want to compare excel sheet value to front end can i do this with get text value plzz rply ….

    • Yes you can if you have code to read data from excel sheet.
      In this process, First figure out text from front end and then compare it with the value fetched from excel sheet and it would work as per my understanding.

  22. Gopi says:

    Assert.assertTrue(enteradmin_email1.getText().contains(p.getVal(“adminemail”)), “Assert Failed as its unable to search text in Logged in Page”);

    I am getting found false in output.

  23. dhirendra singh says:

    Hi sir,
    I am testing android mobile app.
    My customer form is like
    Name,emails I’d ,phone no and address field.
    I want give validation on name field and check its pass or fail
    For name field- its take only 50 char.
    Its does not take null char
    Its does not take special char.

    Please give me right direction.
    Email id-dhirubca.singh@gmail.com

  24. test says:

    On alert pop up, I get message: Please enter username . On next line I get Please enter company name. When I assert it with multiple lines, the assertion fails. How to handle this. If I verify for just one field , I am able to achieve this.

  25. Fabio says:

    Helped me a lot! Thanks!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.