Jason Krept
Jason Krept

Reputation: 165

How do you continue the test after an assertion fails on a test method using TestNG?

I'm trying to figure out a way to close a popup window, even if an assertion fails so my next test can continue from the "main page", or in other words, where I left off.

Here's the workflow: Main page --> Popup window (w/ the assertion below and the driver.close) --> Main page

Currently, if the assertion fails, the popup window remains open and the next test can't find the element it needs to interact with because the element is located on the "main page". I'm open to suggestions. My objective is to provide accurate test results so avoiding false positives is the overall reason why I'm using an assertion.

How do you place an assertion towards the end of a test method, but still have it complete the remainder of the steps, should the assertion fail.

My sample code:

 try{

      WebDriverWait wait = new WebDriverWait(driver,5);
      WebElement Reportrunningalready = wait.until(ExpectedConditions.visibilityOfElementLocated(By.name("btn")));

      System.out.println("Button found. Clicking it now."); 
      driver.findElement(By.name("btn")).click(); }

      catch(Throwable e){
      System.err.println("Button not found within the time.");  
      Assert.assertTrue(driver.getPageSource().contains("Your Report is complete."));


      driver.close();
      // change focus back to old tab
      driver.switchTo().window(oldTab);
      Thread.sleep(3000);

      }

Side note: I realize the getPageSource is not the best way to do it but the popup literally has 5-10 words in the body so it's not that exhaustive.

I'm using TestNG as my framework, Java as my language, and Webdriver2 as my Selenium test harness.

Thank you!

Upvotes: 0

Views: 1868

Answers (2)

Crazyjavahacking
Crazyjavahacking

Reputation: 9677

None of the proposed is a clean solution:

  1. finally is about using a language construct instead of the correct unit testing mechanism
  2. soft assertions are really about gathering multiple errors and providing a meaningful final message, which is not your case either

The correct solution is to clean up the resources in unit testing framework lifecycle methods (in TestNG @AfterMethod or similar annotation)

Upvotes: 1

Nguyen Vu Hoang
Nguyen Vu Hoang

Reputation: 1570

You could use softAssertion, please refer to this post for more information

http://seleniumexamples.com/blog/guide/using-soft-assertions-in-testng/

For continue your test, you should have recover mechanism/initialize steps (such as: go back to login page)

Upvotes: 0

Related Questions