Tips for utilizing one catch block to handle both TestNG assertion errors and RunTime exceptions

In my TestNG framework with Java and Selenium, I have created two custom methods to handle WebElement interactions. Here they are:

// 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);    
}

Let's consider a scenario where clicking on a "Login" link opens a page with username, password fields, and a logout button. Below is a sample code for logging in:

  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
 }
}

The dilemma arises when deciding the exception handling strategy. Using RuntimeException won't catch assert failures but does well with other issues. On the contrary, using AssertionError catches assert failures but not other exceptions. How can I tackle this efficiently without cluttering my code with multiple catch blocks?

Your suggestions and best practices would be highly appreciated.

Answer №1

When it comes to catching exceptions in Java, it’s important to remember that the catch block only catches Throwable objects that extend java.lang.Exception. This means that while AssertionError is an Error (as it extends java.lang.Error), you can still specifically catch AssertionError using the correct syntax:

catch (AssertionError e) { ... }

It’s worth noting that you can’t handle both Exceptions and Errors in the same catch block. However, you can use two separate catch blocks—one for exceptions and one for errors—like this:

try{
...
}catch(Exception e){
...
}
catch(AssertionError e){
...   
}

Answer №2

Here's the response to your query:

You should consider several points listed below:

  1. The method
    isElementPresent(WebElement element)
    is designed to return a boolean value, however, when calling isElementPresent(element);, the returned boolean status is not utilized. It would be advisable to verify the boolean status within a for loop before proceeding with element.click();
  2. The implementation of Assert.assertTrue seems incorrect in this scenario as shown in
    Assert.assertTrue(isElementPresent(logoutBtn));
    . Assertions from TestNG are meant for validating the results of @Test and should not be used within a try block just to catch any failed assertions in the catch block and convert them to 'Pass' status.
  3. To better understand the relationship between try/catch and Assertions, refer to this insightful discussion at this link.
  4. In the provided code snippet, attempting to Assert the presence of the 'Logout' button using
    Assert.assertTrue(isElementPresent(logoutBtn));
    may not be the ideal approach. Instead, consider implementing an ImplicitlyWait or ExplicitWait for the button to become clickable.
  5. To properly implement Assertions, it is recommended to write them outside the try block. Assertions can be applied to elements like Page Title, Page Source, or any other element on a page. Best practices suggest two ways of incorporating Assertions - either include them in the Test Class directly or handle them separately in a dedicated package/class as per PageFactory in POM.
  6. If adding Assertions to your code, consider including one during the initial URL launch and another after logging into the Web Application to validate the Page Title.

If you have further questions or need clarification, feel free to reach out.

Answer №3

The automation framework should handle all assertion, verification, and wait related implementations. Consider using a robust automation framework like QAF. Your code implementation could resemble the following:

// Checks if a WebElement is present on the screen
element.isPresent()
// verify  WebElement is present on the screen
element.verifyPresent()
// assert  WebElement is present on the screen
element.assertPresent()

//actions and other element methods no need to wait
element.click();

QAF also provides a predefined step library that you can leverage. For example, your login function could look like this:

public void login(String username, String pwd){
    //loc provided in locator file
    sendKeys(username, "username.txt.loc");
    sendKeys(text, "password.txt.loc");
    click("login.btn.loc");
}

If you prefer to use BDD:

When send keys 'my text' to 'username.loc' 
And send keys 'my text' to 'password.loc' 
And click on 'login.loc'
They verify 'welcome.msg.loc' is present

For more detailed tutorials, check out the qaf-step-by-step-tutorial

Answer №4

Finally figured out the solution I was looking for! I decided to create a custom assert method :

public void myAssertTrue(Boolean condition){
    try {
        Assert.assertTrue(condition);
    } catch (AssertionError e) {
        e.printStackTrace();
        throw new RuntimeException();
    }
}

I also made adjustments to the isElementPresent Method:

// Checks if a WebElement is present on the screen
public void isElementPresent(WebElement element) {
    try {
        element.isDisplayed();
    } catch (RuntimeException e) {
        throw e;
    }
}

By implementing these two modifications, I am now able to effectively handle both runtime and assertion errors using the RuntimeException catch block.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to start Internet Explorer 11 using selenium version 2.47.1

Upon executing this code in my test automation suite, I encountered the following error: Selenium 2.47.1 Internet Explorer 11 OS: Windows 8 WebDriver driver = new InternetExplorerDriver(); Error Details: While running the code snippet, an issue a ...

Converting HTML Javascript to JAVA with the help of Selenium

Can someone help me extract the value of h1 as a string using selenium? Check out the HTML javascript snippet below- <script type="text/javascript"> $(window).load(function() { var $windowHeight = $(window).height() -12; $(" ...

Getting the attribute value of an element in Playwright using Python: a step-by-step guide

I'm currently working on a project with Playwright Python and I need to retrieve the value of the 'href' attribute for a specific element. In my previous experience with Selenium, I achieved this using: el = driver.find_element_by_xpath("// ...

Storing dynamic dropdown choices using Python and Selenium WebDriver

Struggling with storing address values generated by a postcode lookup for later use in Python's Random module to select a random value using random.choice. Here is the scenario: User enters postcode, clicks 'Search' - dropdown list dynamic ...

Attempting to tap the duplicate option on this disposable email platform

Having trouble with Selenium Every time I run my grab_email() function, I encounter this traceback: Traceback (most recent call last): File "/home/user/PycharmProjects/xxx/run.py", line 19, in <module> grab_email() File "/home/xxx/PycharmPro ...

Using Capybara for testing integration with asynchronous JavaScript

I am currently facing an issue with a failing Rails integration test that has me stumped. The test utilizes Capybara with Selenium as the driver. The specific problem lies in verifying that certain page content is removed after an AJAX call is made. Essen ...

Kindly review the server log for further information. Initial issue: Remote response cannot be parsed

When attempting to conduct tests on GRID3 with appium, I keep encountering this specific error public static AndroidDriver<WebElement> initAndroidDriver() throws Exception { try { String apkLink = SettingsProvider.getPropertyValue ...

Handling exceptions in Selenium

I am in the process of launching a selenium test. However, for some users, there may not be the same number of pages available. This is why I need to implement a try-catch block in my code. Unfortunately, every time he tries and the element is not found, i ...

Changing a nested JSON array into a Java array

I need assistance in converting this JSON Array into a Java class Type array for Android. The goal is to extract all elements from the array, including the "doses" array, and create a Java array. [ { "_id":"58299a0ae1053c391fb95026", ...

Maintain only one instance of WebDriver in C# programming

I am currently working with NUnit 3 and Selenium 3 in VB2015. My project setup involves having a driver creation class, a base class for setup and teardown operations, and separate test classes for different functionalities like clients, invoicing, and est ...

Guide to simultaneously automate two android applications using Appium?

My task involves launching two applications on separate devices. After completing an action in one app, I need to verify it by checking the other app. ...

The erratic performance of the Click() function in Selenium

In my work on a Product automation project (Web CMS), I have encountered inconsistent behavior when using element.Click(). Our setup involves: Selenium + Nunit GUI(unit testing framework) - For running test cases locally on a specific environment Sele ...

Discovering the browser handle for a newly opened IE window in Selenium Java

Currently, I am focused on automation testing using Selenium with Java. In my current scenario, the first step involves opening the login page and then providing credentials before clicking the Login button. After this action is completed, the current brow ...

Steps for choosing a dropdown menu item specified under the <span> tag using Selenium WebDriver and C#

<div class="span3"> <div> LSP Account<br> <span title="" class="k-widget k-dropdown k-header" unselectable="on" role="listbox" aria-haspopup="true" aria-expanded="false" tabind ...

Encountered an issue while attempting to install a Chrome extension using Python with selenium

I want to automate the installation of a Chrome extension using Python Selenium. Whenever I try to click the "Add to chrome" button, a pop-up appears with options to "Add extension" or "Cancel". Despite trying to select "Add extension", I keep encountering ...

Creating a collection by compiling a selection of choices

Presently, I have a piece of code that identifies the Show id, then proceeds to locate the elements in the option tags below it and prints them out individually. WebElement dropDown = driver.findElement(By.id("Show")); List<WebElement> optio ...

Using a Python Selenium script for scraping on Amazon can take up over 10GB of your internet data

I currently have 2500 products stored in a CSV file for Amazon listings. I am using Selenium to automate the process of checking each product to see if the price has changed. While the script is functioning properly, it is consuming 10GB of internet data w ...

The inner loop in Python Selenium fails to iterate through the elements

I have a code that I'm using to scrape data from the BSE website. Everything seems to be working fine except for a small issue. The inner (second) for-loop doesn't seem to iterate and the program ends prematurely. I would greatly appreciate any a ...

Issue with running geckodriver.exe in Selenium 3.8 when using NUnit 3.9

Having trouble running Nunit_selenium automation in the latest version of Firefox, vs 13, selenium webdriver 3.8.0 NUnit3TestAdapter.3.9.0 Selenium.Support.3.8.0 Selenium.WebDriverBackedSelenium.3.8.0 Firefox launches but the driver URL link is not updat ...

Is it possible to implement cascading of AJAX rendered content in JSF 2.0?

For Example: <h:form> <h:commandButton action="#{someBean.someAction}"> <f:ajax render="somePanel"/> </h:commandButton> <h:panelGroup id="somePanel"> <h:commandButton action="#{someBean.otherAction}"> ...