Reputation: 791
I have login form and I need to test it with correct and wrong credentials.
After putting login and password and then clicking on "Log In" button, web-site for 10 seconds it handling.
If credentials are Ok - mainPage.menu WebElement is displayed.
If credentials are wrong - mainPage.menu WebElement is not displayed. Login page could be refreshed or (not always) error message could be shown.
How to check it in the tests?
For correct credentials, test works:
Assert.assertEquals(true, mainPage.menu.isDisplayed());
For wrong credentials, test fails with exception, because mainPage.menu could not be founded:
Assert.assertEquals(false, mainPage.menu.isDisplayed());
If I put in Assert "Log in" button, tests will always be successful, because in any case (any credentials) for first 10 seconds "Log in" is Displayed. Of course, if I put Thread.sleep, it will solve a problem. But, it's not a good practice.
Upvotes: 0
Views: 277
Reputation: 193108
Though this answer will cater to your requirement but ideally valid and invalid logins should be validated in seperate testcases. Additionally, avoid referencing items like mainPage.menu which are true incase of False positives.
Ideal validation candidates can be:
As per your usecase, you need to induce a try-catch{}
block as follows:
try{
Assert.assertEquals(true, <placeholder_of_welcome_message>.isDisplayed());
}catch (NoSuchElementException e) {
Assert.assertEquals(true, <placeholder_of_error_message>.isDisplayed());
}
Additionally, you may need to induce WebDriverWait as follows:
try{
Assert.assertEquals(true, new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.id("welcome_message_element_id"))));
}catch (NoSuchElementException e) {
Assert.assertEquals(true, new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.id("error_message_element_id"))));
}
Upvotes: 1
Reputation: 3927
issue is here
Assert.assertEquals(false, mainPage.menu.isDisplayed());
when credentials are wrong then mainPage.menu
will not be available right, which leads to exception. So need to handle this.Use try/catch
boolean displayed=false;
try {
mainPage.menu.isDisplayed();
displayed=true;
}catch (Exception e) {
//element not displayed
//displayed is false
}
Assert.assertEquals(false, mainPage.menu.isDisplayed());
Upvotes: 1