0

I'm trying to verify if a link is present or not -- but -- if it's not present, I want my script to continue executing (close the browser, etc).

The purpose of my script is to determine if a 'Delete Address' link is present or not. If it is, I click on the link and delete the address. This works fine. If the link is not present however, I just want to continue execution without triggering an exception. My code below triggers an exception if the link is not there.

Thanks for any help...

        try {
            String txt = driver.findElement(By.linkText("Delete Address")).getText().trim();
            Assert.assertTrue(txt.equals("Delete Address"));
            Alert javascriptprompt = driver.switchTo().alert();
            javascriptprompt.accept();
        } catch (NoSuchElementException e) {

        }
RalphF
  • 373
  • 3
  • 10
  • 21
  • let me search that for you: http://stackoverflow.com/questions/6353259/how-do-i-verify-that-an-element-does-not-exist-in-selenium-2 – pogopaule Dec 27 '13 at 18:53
  • 1
    Why cant you just use the exception as knowing that it does not exist....NoSuchElementException??? – ug_ Dec 27 '13 at 18:54
  • I think what OP is asking is for a way to check the existence of an element without the overhead of exception handling. – Jurgen Camilleri Dec 27 '13 at 19:14
  • No, I don't mind having the try/catch structure but when the element is not present, the test is failing. I don't want the test to fail if the element is not present. If the link is present then I want to click it (which is working fine) but if it isn't I don't want it reported in TestNG as a failure. – RalphF Dec 27 '13 at 21:26

2 Answers2

0

I can see several options here

  1. Do not use asserts in the test at all. In this case the test is marked as successful (if you caught exceptions)

  2. If you want the lines after the findElement() call be executed you can

    • move all lines expect for findElement() out of the try {} clause
    • use the try {} catch {} finally {} construction and put to the finally {} clause all the code you want to be executed, no matter what happens in the try {}
  3. If you want to avoid catching exception, you can create a listener class by implementing the interface ITestListener and in onTestFailure() obtain the exception using getThrowable()

    String stackTraceString = Throwables.getStackTraceAsString(getCurrentTestResult().getThrowable());

Then, if the exception is NoSuchElementException then set test result to success

result.setStatus(ITestResult.SUCCESS); 
setCurrentTestResult(result);
Vlad.Bachurin
  • 1,340
  • 1
  • 14
  • 22
0

Another solution would be to use .findElements. It will return an empty collection, as opposed to throwing an exception, if there are no elements found with the given selector.

Arran
  • 24,648
  • 6
  • 68
  • 78