Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
2 views
in DevOps and Agile by (47.6k points)

I want to use Assertion in selenium web driver test because on my screen, I have one 'edit' button, but that 'edit' button works only on certain conditions. So I just wanna check if that button is present, and if it is, then it should be clicked on and it should open another child window and perform certain actions. But, if that 'edit' button element is not present, then it should check the next condition which is log off button in my keyword framework. Below is my code, and I have used to try and catch block and its working fine:

public void click_edit_cw2(String objectName)  {

        //Store the current window handle

        String winHandleBefore = driver.getWindowHandle();

        //Perform the click operation that opens new window

        try{

            WebElement element = driver.findElement(By.xpath("//*[@id='main']/div[1]/table/tbody/tr[2]/td[6]/button"));

        element.click();

        driver.findElement(By.xpath("//*[@id='main']/div[1]/table/tbody/tr[2]/td[6]/button")).click();

        //Switch to new window opened

        for(String winHandle : driver.getWindowHandles()){

            driver.switchTo().window(winHandle);

        }

        // Perform the actions on new window

        driver.findElement(By.xpath("//*[@id='myModal']/div/div/div[2]/form/div/div[10]/div/button[1]")).click();

        //Close the new window, if that window no more required

        //driver.close();

        //Switch back to the original browser (first window)

        driver.switchTo().window(winHandleBefore);

        //continue with original browser (first window)

        }catch(Exception excptn){

            driver.findElement((By.xpath("//*[@id='logoutForm']/ul/li[2]/a"))).click();

    }

    }

But it didn't work for me with assert even though try() and catch() is not stopping the code. But after running the execution, it says test cases failed. How can assert that? I'm using the keyword framework in which one class is for keyword and the other is for reading the excel file.

1 Answer

0 votes
by (106k points)

If you want to use assertion in selenium web driver, you will need to implement test frameworks like TestNG or JUnit. It is good to use TestNG and once the libraries are imported, you can run the below-mentioned command:

Assert.assertTrue(driver.getWindowHandles().size().equals(2));

After following all the above steps if the assertion fails, it means your test case fails. This is one way of using assertion web driver, but since your using a keyword-driven framework, you could modify the above line as per your wish and get assertion working.

Browse Categories

...