Wednesday, April 17, 2013

What is the difference between WebDriver.close() and WebDriver.quit()

WebDriver.close() method closes the current window.

See the below example, here it opens the new link in a different window and upon executing the close() method, it closes the parent window and leaving the new window open.

WebDriver driver=new FirefoxDriver();
driver.get("http://google.com");
driver.manage().window().maximize();
WebElement oWE=driver.findElement(By.linkText("About Google"));
Actions oAction=new Actions(driver);
oAction.moveToElement(oWE);
oAction.contextClick(oWE).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).build().perform();
driver.close();

Whereas, WebDriver.quit() method quits the driver, and closing every associated window.
In the above example, if you use driver.quit() in place of close , then first opens "google" page and then open the "about google" in new window and closes both the windows.

Tuesday, April 16, 2013

How to check the object existance

Here in the below code, i am checking for an object existence.

    //Max_TimeOut variable holds the time in seconds for the maximum time to wait before the control flows to NoSuchElementException block.
    int Max_TimeOut=60;
    public boolean isObjExists(WebDriver driver,By locator)
    {
        //I am putting the code in try catch because if the object does not exist, it throws exception.
        try
        {
            //Before throwing exception, it will wait for the Max_timeout specified
            WebDriverWait wait=new WebDriverWait(driver,Max_TimeOut);
            wait.until(ExpectedConditions.elementToBeClickable(locator));
            //If the element found, then it returns true
            return true;
        }
        catch(NoSuchElementException exception)
        {
            //If the element is not found, then it returns false
            return false;
        }
       
    }

This function can be invoked in like below:
        By locator=By.name("Email");
        if(obj.isObjExists(driver, locator))
        {
            Reporter.log("Object exists");
            WebElement uNameElement=driver.findElement(locator);
            uNameElement.sendKeys("abcd");
        }
        else
        {
            Reporter.log("Object does not exist");
        }