简体   繁体   中英

TestNG - Why does testNG reporter not print out else statements?

I am trying to check whether the submit button on my login form is pressed when the correct details are put in. I also want to check when the login details fail to print a message to the NGreporter that the login failed. My code is below:

WebElement  login = driver.findElement(By.id("dijit_form_Button_1_label"));

Assert.assertTrue(login.isDisplayed());

if(login.isDisplayed()){
  login.click();
  Reporter.log("Login Form Submitted  | ");
} else { 
  Reporter.log("Login Failed  | ");
}

When the correct details are entered it will print Login form Submitted to the reporter, however, when it fails it does not print Login Failed to the reporter.

Maybe I am using isDisplayed wrongly for checking weather a submit was successful or not?

The reason the else block never executes is because Assert.assertTrue(...) throws an AssertionError when login.isDisplayed() is false. As a result, the if-else block is never reached when login.isDisplayed() is false, only when it is true (in which case only the if portion is executed).

The quickest way to achieve what you want is to move the assertion line below the if-else block, like so:

WebElement  login = driver.findElement(By.id("dijit_form_Button_1_label"));

if(login.isDisplayed()){
  login.click();
  Reporter.log("Login Form Submitted  | ");
} else { 
  Reporter.log("Login Failed  | ");
}

Assert.assertTrue(login.isDisplayed());

And if you want to avoid making asserting twice that login.isDisplayed() returns true then you can use Assert.fail() inside your else block:

WebElement  login = driver.findElement(By.id("dijit_form_Button_1_label"));

if(login.isDisplayed()){
    login.click();
    Reporter.log("Login Form Submitted  | ");
} else {
    Reporter.log("Login Failed  | ");
    Assert.fail("Login was not displayed");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM