I will try to give as much information as possible. I'm using TestNG framework with Java.+Selenium Below are 2 custom methods i have written.
// Checks if a WebElement is present on the screen
public boolean isElementPresent(WebElement element) {
try {
element.isDisplayed();
return true;
} catch (RuntimeException e) {
return false;`
}
}
// Used to click on the desired element
public void clickWebElement(WebElement element) {
isElementPresent(element);
element.click();
}
protected void enterDataintoField(WebElement element,String fieldData) {
isElementPresent(element);
element.click();
element.clear();
element.sendKeys(fieldData);
}
Now assume there is a link say Login. Clicking on Login opens a page which has 2 fields username and password.The below code is used to login.(Login, username ,password and logoutBtn are webElements)
public void login(String username, String password)
{
try{
clickWebElement(Login);
//pause few seconds for page load
enterDataintoField(username, "Adam");
enterDataintoField(password, "mypassword");
//pause few seconds to login
Assert.assertTrue(isElementPresent(logoutBtn));
}catch({**ErrorType**} e){
//Some code here
}
}
Now comes my issue. If i set the ErrorType to RuntimeException in the above catch block then incase of any issues like say the username field is not displayed or the login button is missing, then this catch block will be able to catch the issue. BUT this catch block will not be able to catch the Assert statement above which validates whether the login was successful.
Similarly if i use AssertionError above then the catch block will be able to catch scenarios where the assert fails but will not be able to catch any other issues. Hence i need some advice on what i can do here. I have thousands of lines of code so i don't want to use both RuntimeException and AssertionError catch blocks everywhere(As in 2 catch blocks. I want a single catch block)
Any other suggestion or best practice would be really appreciated.