Is it feasible in Selenium to report a failure for a particular test case step and carry on with the rest of the steps if necessary?

Is it possible to report and continue with remaining steps in Selenium if a step fails for a test case? The current behavior halts the execution if there is an exception. Below is an example of how a test case looks like:

public class TC002_abc extends OpentapWrappers
{       

    @Test (description="Test")
    public void main() 
    {

        try
        {             
            WebDriverWait wait=new WebDriverWait(driver, 60);     
            VerifyTitle(Constant.HomePage_Title);  
            Click(HomePage.link_Login(driver), "Login Link");           
            wait.until(ExpectedConditions.urlContains(Constant.LoginURL));    
            VerifyTextPopulated(CommunicationPref.lbl_EmailAddress_Input(driver), Constant.EmailAddress);       
            /* Validate Email Communications */                 
            Click(CommunicationPref.link_EditEmailCommunications(driver),"Edit Email Communications");
            VerifyText(CommunicationPref.lbl_UnCheckedEmailCommunications(driver), Constant.UnCheckedEmailCommunications_Text);
            Click(CommunicationPref.btn_EmailCommunicationsSave(driver), "Save");                           
            VerifyText(CommunicationPref.lbl_CheckedEmailCommunications(driver), Constant.CheckedEmailCommunications_Text);               
        }
        catch (NoSuchElementException e) 
        {
            e.printStackTrace();
            Reporter.reportStep("NoSuchElementException" , "FAIL");         
        }
    }

    @BeforeClass
    public void beforeClass()
    {
        browserName="firefox";
        testCaseName = "TC002_abc";
        testDescription = "Test";
    }

}

Sample Method-

public static void VerifyTitle(String title){

    try
    {       

        if (driver.getTitle().equalsIgnoreCase(title))
        {           
            Reporter.reportStep("Page is successfully loaded :"+title, "PASS");                     
        }
        else

            Reporter.reportStep("Page Title :"+driver.getTitle()+" did not match with :"+title, "FAIL");

    }
    catch (Exception e) 
    {
        e.printStackTrace();
        Reporter.reportStep("The title did not match", "FAIL");
    }

}

Answer №1

To enhance your TestNG usage, consider incorporating a Soft Assertion technique.

public void CheckPageTitle(String expectedTitle)
{

     SoftAssert softAssertion = new SoftAssert();
     String actualTitle = driver.getTitle();

     if (softAssertion.assertTrue(actualTitle.contains(expectedTitle)))
     {

          Reporter.log("The page has loaded successfully with title: " + expectedTitle, "PASS");

     } else
     {

         Reporter.log("Page Title doesn't match. Expected: " + expectedTitle + ". Actual: " + actualTitle, "FAIL");
     }
}

Please try implementing this and let me know if it solves your issue.

Answer №2

Is it possible to report a failure for a specific test case step and continue with the remaining steps?

Short answer: YES Long answer: YES

Selenium is a framework that relies on test engines like JUnit or TestNG. If no action is taken, these engines will assume the test passed by default. The same principle applies to Selenium. The code snippet below demonstrates how a Cucumber step would be structured.

@When("my test step here")
public void myTestStep(...) {
    boolean result = false;
    try {
            result = myTest(...);
        }
    } catch (Exception e) {
        // log any exceptions without throwing them
    }
    if (result) {
        // log passing test
    } else {
        // log failing test
        Assert.fail(); // Removing this line allows testing to continue after a failure.
}

The approach for JUnit or TestNG methods is similar. An @AfterClass or @AfterTest hook can dictate whether the test passes or fails. By default, passing assertions are implicit, while failing assertions must be explicitly included (look for instances of Assert.fail()). A more flexible option is to add a configurable property to your test suite for enabling or disabling fail assertions.

    } else {
        // log failing test
        if (skip_off) {
            Assert.fail(); // Removing this line allows testing to continue after a failure.
        }
}

In this scenario, skip_off represents a Boolean property in a configuration file. When set to true, it bypasses fail assertions.

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

Guide on utilizing JavaScript to modify the attribute of a chosen web element with Selenium WebDriver in Java

I am seeking a way to utilize Javascript in order to set attributes for the selected element on a webpage. After some research, I have discovered two methods for achieving this with Javascript: Method 1 WebDriver driver; // Assigned elsewhere Jav ...

When an assertion fails in Selenium Webdriver, it may lead to the inability to proceed

I need the execution to continue until the end even if the Assert condition fails in my Selenium WebDriver Script. Currently, when the Assert condition fails, it stops executing the remaining code. Below is the code that I have written. Any suggestions? ...

Troubleshooting issue with setting browser version using Selenium Add Additional Capability in .NET Framework not resolving

I am currently working on testing my program across various browser versions. To begin, I opted to use ChromeDriver by implementing the following code: using OpenQA.Selenium.Chrome; ChromeOptions Options = new ChromeOptions(); Options.PlatformName = " ...

The inconsistency of Selenium's StaleElementReferenceException error and the variability of pageload completion codes is causing issues with clicking on elements

Big shoutout to the amazing stackoverflow community for always providing assistance. Lately, I've been grappling with the frustrating "StaleElementReferenceException" issue and haven't found a universal solution yet. Some helpful members have rec ...

Having issues with your Spring Boot POST request functionality?

I have been working on developing a Spring Boot REST application with AngularJS. Everything seems to be loading properly, all JS and CSS files are included. However, I am experiencing an issue where GET requests work fine, but POST requests fail and do no ...

Utilizing Xpath to locate checkboxes

I'm currently exploring Selenium and aiming to select a checkbox on Amazon's webpage. Upon visiting the Amazon site, I searched for dresses. On the left-hand side, it shows different brands, and I specifically want to choose the Relipop checkbox. ...

Is there a way to exclude a specific Base class from the serialization process in Struts JSON?

To serialize properties up to the base class (2 levels), you can use the following method: public class BaseRoot{ String prop1; //getter and setter } public class SubClass extends BaseRoot{ String prop2; //getter and setter } public class ActionClass ...

Is it possible to utilize Nightwatch for testing Rails?

Recently, a contractor working on our startup project implemented the Selenium-based Nightwatch testing framework due to our heavy reliance on React. However, there seems to be conflicting opinions about whether it can effectively test our Rails code. One ...

Skip a single test from a suite in Firefox using Protractor automation framework

I have a collection of tests in my tests folder, all named with the convention ending in spec.js. By using the */spec.js option in the Config file, I am able to run all tests seamlessly. However, I encountered an issue where I needed to skip running a spe ...

The Java Selenium code seems to be having trouble launching the web browser

I am a beginner in selenium and attempting to open in the chrome browser using selenium (see code below). However, I am not seeing the chrome browser display after running this code. Can someone point out what's wrong with this code? Below is the co ...

The error message `org.openqa.selenium.StaleElementReferenceException: element is not attached to the page document while navigating a List` indicates that the

Can someone help me troubleshoot this error that keeps popping up? I need assistance fixing it. The website I'm currently working on is: "". While navigating through this site, the following code snippet generates an error: List<WebElement> cl ...

Quick method for handling arrays to generate waveforms

I'm currently working on optimizing the code for my web application. While it functions, the performance is a bit slow and I am looking to make improvements: The main concepts behind the code are: The function retrieves the current buffer and conve ...

Is it possible to make a post using selenium?

I am looking for a way to implement the POST method in Selenium, similar to how it is done using requests for fast login. I have successfully logged in using `requests.post`. In requests: session = requests.session() session.post(url, data=data, headers=h ...

The position specified is not within the valid range of the collection. The index must be a non-negative value and less than the size of the collection. Please check

As a novice in Selenium with C#, I encountered an issue while using the code snippet below. The exception thrown was: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index I would greatly appreciate ...

Changing the user agent string dynamically in chromedriver using selenium at runtime

I have a project that requires me to modify the user agent. Initially, I provided the user agent as... (to chromedriver) options.addArguments("--user-agent=Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mob ...

Decoding a JSON object into a generic collection

I have developed the following DTO classes in Java: public class AnswersDto { private String uuid; private Set<AnswerDto> answers; } public class AnswerDto<T> { private String uuid; private AnswerType type; private T value ...

What are the possible reasons for the Selenium GECKO driver failing to start the server on Firefox 48?

In our .Net Automation Testing Project, we were using Selenium 2.5.3 along with a NUnit Test project successfully with Firefox version 47. However, after upgrading to Firefox 48, we started encountering issues. I downloaded the Gecko.exe (version 9) from ...

Selenium and Chromedriver in Python encountered a WebDriverException with the message "target frame detached error."

Currently, I am working on a parsing program using Python and Selenium. I encountered the following error: Traceback (most recent call last): File "/Users//Desktop/babushkabot.py", line 123, in <module> bot.polling() File "/Li ...

Accessing Gmail inbox through Selenium WebDriver in Java for opening emails

Is there a method in Selenium WebDriver with Java in the Eclipse IDE that allows for opening Gmail inbox emails using XPath? ...

Experiencing difficulties with Python Selenium in Opera browser when trying to access Youtube

I have been experimenting with the code found on this URL, and it seems to be functioning well for Opera browser- Driving Opera using Selenium in Python import time from selenium import webdriver from selenium.webdriver.chrome import service webdriver_s ...