manjunath
manjunath

Reputation: 11

Compare two strings in selenium

I need to take value from row from page

my code is

String bname1 = selenium.getText("//table[@id='bank']/tbody/tr[3]/td[2]");
assertEquals(bname1,"HDFC");
if(bname1=="HDFC") {
    System.out.println("Bank name is:"+bname1);
} else {
    System.out.println("Bank name not found");
}
System.out.println(bname1);

Result: Bank name not found HDFC

My bank name is "VIJAYA" But when i compare to "bname1" and "VIJAYA",RESULT will be negative? How can i compaire these strings pls help me...

Upvotes: 0

Views: 70799

Answers (5)

Sudheer Singh
Sudheer Singh

Reputation: 654

You can simply use assertions like:

Assert.assertEquals(ExpectedString, ActualString);

Here ExpectedString is a string that is expected and ActualString is original String value.

Upvotes: 0

Kingsley
Kingsley

Reputation: 63

I'm sure It will help you

assertEquals(bname1,"HDFC");
if(bname1.equals("HDFC")) {
    System.out.println("Bank name is:"+bname1);
} else {
    System.out.println("Bank name not found");
}
System.out.println(bname1);```

Upvotes: 0

Chinna
Chinna

Reputation: 1

Try this..

        WebDriver driver = new FirefoxDriver();
        driver.navigate().to("Url");

        WebElement strvalue = driver.findElement(By.xpath("  "));
        String expected = "Text to compare";
        String actual = strvalue.getText();
        System.out.println(actual);

    if(expected.equals(actual)){
        System.out.println("Pass");
    }
        else {
            System.out.println("Fail");
        }

Upvotes: 0

Aaron Levenstein
Aaron Levenstein

Reputation: 395

Your original code has some other issues as well. When you call assertEquals() that tells the compiler to check if the two values are equal and then stop executing code if the condition is not true. Because of this the print statements found after your assertEquals() statement will not get executed if the assertion fails. Instead you should try to do something like the following.

String bname1 = selenium.getText("//table[@id='bank']/tbody/tr[3]/td[2]");
assertEquals("Bank name - "+bname1+" should be HDFC",bname1,"HDFC");

If you write your statement like this the first parameter of the assertEquals function will become the error message displayed when the assertion fails.

Upvotes: 0

aroth
aroth

Reputation: 54806

You cannot compare strings in Java using ==. All that does is test to see if the two objects have the same address in memory/are the same instance. Use .equals() instead, like:

if(bname1.equals("HDFC"))

...or preferably:

if("HDFC".equals(bname1))

Which is better because it won't crash if 'bname1' is null.

Upvotes: 10

Related Questions