当输入正确的详细信息时,我正在检查登录表单上的提交按钮是否被按下。我还想检查登录详细信息何时无法向NGreporter打印登录失败的消息。我的代码如下:
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 | ");
}
当输入正确的详细信息时,它将打印登录表单Submitted to the reporter,但是,当它失败时,它不会打印Login Failed to the reporter。
也许我错误地使用isDisplayed来检查提交是否成功?
else块从不执行的原因是,当login.isDisplayed()
为false时,Assert.assertTrue(...)
抛出一个AssertionError。因此,当login.isDisplayed()
为假时,仅当它为真时(在这种情况下,仅执行if部分),就永远不会到达if-else块。
实现所需内容的最快方法是将断言行移动到if-else块下方,如下所示:
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());
如果你想避免两次断言login.isDisplayed()
返回true,那么你可以在其他块中使用Assert.fail()
:
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");
}