0

In some instances, the getTitle() method does not work for me.

Take a look.

@Test
public void testTitleReliability() {

    driver.get("https://www.google.com");

    boolean title = driver.getTitle() == "Google";

    if(title)

        System.out.println("I am working correctly");

    else if(!title)

        System.out.println("I am broken!");

However, it will work with this:

@Test
public void testTitleReliability() {

    driver.get("https://www.google.com");

    boolean title = driver.getTitle().contains("Google");

    if(title)

        System.out.println("I am working correctly");

    else if(!title)

        System.out.println("I am broken!");

Anyone know why?

1
  • This is more of a Java programming question than a QA question.
    – user246
    Commented Feb 27, 2014 at 21:30

2 Answers 2

9

The "==" operator checks objects for identity, not for equality. Try this instead:

driver.getTitle().equals("Google")
2

This has nothing to do with getTitle() from selenium web driver. This is how string comparisions work.

When you use an double equals operator on two objects(strings in this case), their addresses will be compared to see if they are same objects. when I say same objects, a two different objects can contain exactly same data.

When you use contains on a string, that will verify contents of the string character by character irrespective of their addresses.

There is another angle to this discussion. Is title exactly equal to "Google" or is it going to something like "Google " with additional space or something like that, if that is the case you can't use equals. however if they are exactly equal, you can also use getTitle().equals("Google") as the other answer already pointed out.

This is the reason you contains works where as ==doesn't.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.