Java HTMLUnit Testing Navigation Buttons

I'm quite new to Selenium HTMLUnit so I'm looking for some help in creating a basic test for a navigation button in my Spring Boot app.

I'm trying to put together some basic tests to make sure that the navigation buttons in my webapp work as expected. My approach to this is to find the required navigation button by Id, click it, then check that the current URL is the new page I was expecting to be on.

...
private HtmlUnitDriver driver = new HtmlUnitDriver(true);
...

@Test
public void navigationTest() {
    driver.get(BASE_URL);

    WebElement button = driver.findElement(By.id("navigation_button_id"));
    button.click();

    String currentUrl = driver.getCurrentUrl();

    Assert.assertThat(currentUrl, is(BASE_URL + "some_other_page"));
    driver.close();
}

I've attempted to use the .click() method (shown above), I've also attempted to use an Actions object instead of the simpler .click() method (see below) to perform the navigation but this still did not work.

Actions actions = new Actions(driver);
actions.click(button).build().perform();

The behaviour at the moment is that the URL is not changing from the BASE_URL (e.g. http://localhost:8080), I have verified that it works manually (clicking around in person) but I can't get the test to click the button and tell me that the URL has changed (showing that the user has been taken to the new page e.g. http://localhost:8080/some_other_page).

Can anyone offer some advice to get this working? I just need the simplest means of testing basic navigation is working in HTMLUnit.

2 answers

  • answered 2018-04-14 14:33 Siraj K

    The way I remember doing it is to wait/ assert for the new page to load. If you can't do that, add a wait of few seconds before getCurrentUrl()

  • answered 2018-04-14 14:33 cruisepandey

    I would suggest you to use below code for Navigation purpose :

    To go forward :

    driver.naviagte().forward();  
    

    To go backward :

    driver.navigate().back();  
    

    For solving your issue , when you are going forward/backward : Wait for some element by using this code :

    WebDriver wait = new WebDriverWait(driver, 10);
    wait.until(ExpectedConditions.visibilityOfElementLocated("some element locator"));  
    

    Then get the currentUrl by using driver.getCurrentUrl(); code.

    Hope this will help you to resolve your issue.
    Please let me know if you have any concerns related to this.