Student
Student

Reputation: 531

TestNG try/catch not working properly

I am working on a test automation framework that someone previously built. The framework reads test data from an excel file and uses Selenium webdriver to control the browser and perform tests.

I am adding functionality to this framework by adding a TestNG class that reads data from a CSV file. Some functions in the current framework use try/catch. So when I call these functions from the TestNG class, TestNG will always say that the test passed, no matter what.

For example, this is from the current framework;

    if (enterValueInBox.length() >= 1) {
        try {
            browserActions.typeValueInTextBox(myDriver, enterValueInBox);
        } catch (Exception e) {
            System.out.println("enterValueInBox failed");
        }
    }

This if statement is inside a function. It doesn't matter whether this functions works or not, it will always pass in TestNG. Even if Selenium can not find the element for example.

How can I work around this? Do I have to change the try/catch?

EDIT: Another example from the same function. The function basically consists of several if statements just like the two I am showing here. They all have the same signature, so an if statement with try/catch inside. Also worth mentioning, the function/class I am calling is not a TestNG class. So I built a TestNG class, and calling a non-TestNG class->method.

   if (backSpaceInTextBox.length() > 1) {
        try {
            wa.handleSeleneseCommand(myDriver, Properties.TIME_TO_WAIT,
                    "niet gelukt");
            browserActions.doBackSpaceInTextBox(myDriver,
                    backSpaceInTextBox);
        } catch (Exception e) {
            System.out.println("Could not do backspace");
        }
    }

Upvotes: 1

Views: 4200

Answers (2)

Bartosz Bilicki
Bartosz Bilicki

Reputation: 13265

Your tests are passing because test function completes

  • without any assertion failures
  • without exception thrown from test method

In your case, you should do one of

  • do not catch exceptions at all. Declare test methods to throw those exceptions
  • catch exception and fail test (Assert.fail)

Upvotes: 2

ToYonos
ToYonos

Reputation: 16833

Try this :

if (enterValueInBox.length() >= 1)
{
    try
    {
        browserActions.typeValueInTextBox(myDriver, enterValueInBox);
    }
    catch (Exception e)
    {
        Assert.fail("EnterValueInBox failed", e);
    }
}

Your test will fail when an Exception is thrown.

Upvotes: 2

Related Questions