Exception Handling with TestNG and Selenium

204 views
Skip to first unread message

Ryan McNeely

unread,
Feb 23, 2016, 3:25:24 AM2/23/16
to testng-users
Hi All,

I'm trying to get a handle on best practices for using Exception Handling in my Java TestNG Selenium scripts. I think it would be good to have Try Catch blocks around all of my findElement and sendKeys and click methods. I figure if my script cannot find the element it's looking for, I want to handle it.

If so, could you point me to the correct API documentation for doing this?

If not, why? And is there any other case in Selenium scripts where we want Exception Handling?

Thanks,
Ryan

sunny sachdeva

unread,
Feb 23, 2016, 5:22:56 AM2/23/16
to testng-users
What I normally do is to have my webdriver methods throw exception and I catch them in respective testng test cases. This way I can know why and at which point my test cases failed.

For selenium webdriver specific exception you can take a look at 

Hope this helps
Thanks
Sunny
Message has been deleted

Ryan McNeely

unread,
Feb 24, 2016, 6:30:20 AM2/24/16
to testng-users
Thanks Sunny,

So I think you're referring to something like this for your test class...

public class TestClass{

   @Test
   private void testMethod(){
       UtilClass.testMethod()
   }
}

And something like this for your method...
package com.test
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class UtilClass{
  public static void testMethod() {

    try {

        log.info("Clicking button.");

        driver.findElement(By.id(button_id)).click();

    } catch (NoSuchElementException e) {
        log.error("Unable to locate button.", e);
        Assert.fail();
    }
}

Ryan McNeely

unread,
Feb 24, 2016, 6:30:59 AM2/24/16
to testng-users
Also, would you ever use (Exception e) to catch all exceptions? Why or why not?


On Tuesday, February 23, 2016 at 2:22:56 AM UTC-8, sunny sachdeva wrote:
Reply all
Reply to author
Forward
0 new messages