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:
- Selenium WebDriver with Java -Basics to Advanced+Frameworks
- Selenium WebDriver With Java – Novice To Ninja + Interview
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.
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
@Deepali could you please elaborate your probolem, and what kind og lgs u r comparing
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<mpl=default<mplcache=2&emr=1&osid=1#identifier”);
String PageTitle = driver.getTitle();
Assert.assertEquals(PageTitle, “Gmail”);
Regards,
Srinivasarao
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!!
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
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 “);
}
how to write this assert result in excel as pass fail status?
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.
Hello Sir,
How to verify the slide show images on webpage using selenium webdriver.
For that purpose you can use the OMR binaries of java to read content of Image to verify.
So for that I would write one post all about validating Images through its content.
Thank you !!
Thnkx mate. Your blog is very help full.
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”);
}
Hello Sir,
Could you please elaborate more on how to verify text on images in selenium
Thanks,
Niharika
Hi please add me on your blog..
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
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
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.
In this case first read the data from site second thing is to read data from
Excel sheet using any api either poi or jxl and then call assertequal assertion and put both values if both string would be same it will pass otherwise assert will fail.
Thanks for reply
can u pls provide sample code(snippet) to understand.
Yes drop a mail
On my mail
Id dwarika1987@gmail.com
i sent you my mailID can u pls send the sample piece of code.
it will be great helpful to me
I dropped a mail to ur mailID.please check and help.
thanks very much
am waiting for reply.
Check your mail, I have mailed your solution..
For more query you may contact me any time.
hi
Is there any way to download the files from applications and save it local drive with selenium webdriver.
if there is a way pls help me in giving a solution.
Advance thanks
For such kind of action you can use robot class or autoit.. Internet is filled with such kind of articles
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
Hi Mishra,
I m waiting for you reply. I hope you will reply soon.
Thanks
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
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 ?
Could you please sens in your complete code on dwarika1987@gmail.com
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).
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
Could you please elaborate it so that i could understand your context
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
For the same use BufferedReader and i would suggest go and read about
This
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?
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.
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.
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
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.
Helped me a lot! Thanks!