0

I am trying to click a login button using HtmlUnit 2.23, using either DomElement or executeJavaScript but none of it works. Is there any other way to get it working? This is the code:

@Test
public void noLogin() throws Exception {
    final WebClient webClient = new WebClient(BrowserVersion.BEST_SUPPORTED);
    //see http://stackoverflow.com/questions/3600557/turning-htmlunit-warnings-off/18563576#18563576
    java.util.logging.Logger.getLogger("com.gargoylesoftware").setLevel(Level.OFF); 
    //see http://stackoverflow.com/questions/18556200/htmlunit-button-click
    webClient.getOptions().setJavaScriptEnabled(true);      
    webClient.getOptions().setThrowExceptionOnScriptError(false);
    webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
    webClient.setAjaxController(new NicelyResynchronizingAjaxController());

    final HtmlPage loginPage = webClient.getPage("https://sandbox.paydirekt.de/account/#/login");
    loginPage.getElementById("username").setAttribute("value", "no");
    loginPage.getElementById("password").setAttribute("value", "login");
    //final HtmlPage welcomePage = ((DomElement)loginPage.getFirstByXPath("//button[@type='submit']")).click();
    //see http://stackoverflow.com/questions/14474580/use-htmlunit-doesnt-work-button-click
    //ScriptResult result = loginPage.executeJavaScript("javascript:document.getElementsByName('loginForm')[0].submit();");

    ScriptResult result = loginPage.executeJavaScript("javascript:document.getElementsByClassName('loginBox__loginButton button button--full')[0].click()");
    Page page = result.getNewPage();
    if (page.isHtmlPage()) {
        HtmlPage welcomePage = ((HtmlPage)page);
        System.out.println(welcomePage.asText());
        Assert.assertTrue(welcomePage.asText().contains("Benutzername oder Passwort nicht korrekt."));
    }
    webClient.close();
}
Würgspaß
  • 4,660
  • 2
  • 25
  • 41

1 Answers1

0

You can also use the connection wrapper that HTMLUnit offers to check for each request and response manually. Here is an example

            new WebConnectionWrapper(webClient) {

                public WebResponse getResponse(WebRequest request) throws IOException {
                    WebResponse response = super.getResponse(request);
                    if (request.getUrl().toExternalForm().contains("THE URL YOU WANT TO CHECK")) {
                        String content = response.getContentAsString("UTF-8");

//CHECK CONTENT HERE


                        WebResponseData data = new WebResponseData(content.getBytes("UTF-8"), response.getStatusCode(),
                                response.getStatusMessage(), response.getResponseHeaders());
                        response = new WebResponse(data, request, response.getLoadTime());
                    }
                    return response;
                }
            };
Arya
  • 8,473
  • 27
  • 105
  • 175