equals() doesn't work as expected with Selenium

I am trying to compare current URL with a string URL, but the following code returns false.

driver.get("https://www.facebook.com");       
System.out.println(driver.getCurrentUrl().equals("https://www.facebook.com"));

Solution 1:

I tried your code, and the URL that is being returned by driver.getCurrentUrl() was "https://www.facebook.com/"

Since you are doing an equals check with "https://www.facebook.com", it will return false because of the missing '/' at the end of returned URL. Either compare it with this URL being returned, or use contains() to check if url returned is correct.

Solution 2:

Instead of using equals() try to use startsWith():

driver.getCurrentUrl().startsWith("https://www.facebook.com")

or contains():

driver.getCurrentUrl().contains("https://www.facebook.com")

This approach will be much better.
For using equals() you need to have exactly the same path which you expect.

However with contains() or startsWith() you can check expected behaviour and make an assertion.

I created some demo code:

public class FacebookDemoTest {

    private WebDriver driver;

    @BeforeMethod
    public void setUp() {
        driver = DriverManager.getInstance();
        driver.get("https://www.facebook.com");
    }

    @Test
    public void testContainsAndStartsWith() throws Exception {
        System.out.println("CURRENT URL:" + driver.getCurrentUrl());

        Assert.assertTrue(driver.getCurrentUrl().contains("https://www.facebook.com"));
        Assert.assertTrue(driver.getCurrentUrl().startsWith("https://www.facebook.com"));
    }

    @Test
    public void testEquals() throws Exception {
        System.out.println("CURRENT URL:" + driver.getCurrentUrl());

        Assert.assertTrue(driver.getCurrentUrl().equals("https://www.facebook.com"));
        Assert.assertTrue(driver.getCurrentUrl().contentEquals("https://www.facebook.com"));
    }

    @AfterMethod
    public void tearDown() throws Exception {
        DriverManager.closeQuietly();
    }
}

Here is results:

enter image description here

and current URL from console log:

CURRENT URL:https://www.facebook.com/