Thursday 5 June 2014

TestNG Soft Assertions

Instead of writing a custom logic, the TestNG library itself offers the facility to perform Soft Assertions in your test.

To use testng soft assertion, you have to use testng SoftAssert class. This class will helps to not throw an exception on assertion failure and recording failure. If you will use soft assertion then your test execution will remain continue even If any assertion fails. Another most Important thing Is your assertion failure will be reported In report so that you can view It at end of test. You can use soft assertion when you are using multiple assertions In same test method and you wants to execute all of them even If any one In between fails.


SoftAssert s_assert = new SoftAssert();

  
@Test
   //In this method, Test execution will not abort even If any assertion fail. Full Test will be executed.
   public void soft_assert_text() {
   Actualtext = driver.findElement(By.xpath("//h2/span")).getText();
   //Text on expected side Is written Incorrect intentionally to get fail this assertion.
   s_assert.assertEquals(Actualtext, "Tuesday, 01 January 2014", "1st assert failed.");
   System.out.println("Soft Assertion -> 1st pagetext assertion executed."); 

Custom wait for element function for web driver

Web driver does have inbuilt functions to wait for the presence or even visibility of element on screen. However, at time we come across situations where non of the built in methods really work.

So here below is a custom method that is designed to use with any type of selenium webdriver frameworks. Lets have a look at the method::


public static void waitForEelement(final By locator, int timeOut) {

        for (int second = 0;; second++) {

            if (second >= timeOut) fail("timeout waiting for element");

            try {

                 if ((getSelenium().getWrappedDriver().findElements(locator).size()) > 0){

                     break;

                }

                } catch (Exception e) {}

            try {

                Thread.sleep(1000);

            } catch (InterruptedException e) {

                 e.printStackTrace();

            }

        }

      

    }


This method can be called upon as follows:

waitForEelement(By.xpath("//div[@class='signin']"),60);