Friday, 9 May 2014

Selenium WebDriver Methods Examples

Selenium WebDriver Methods Examples

1.Browser Back and Forward (NAVIGATION)

 

Steps to implement Browser back and forward through Selenium Web Driver
1. Create Driver for any Browser(Mozilla or Chrome)
2. Go to the URL
3. Navigate to some page in website.
4. Use Selenium code to Navigate Back to Main Page.
CODE: driver.navigate().back();
           driver.navigate().forward();
Example

WebDriver driver =new FirefoxDriver();
driver.get("http://seleniumhq.org/");
driver.findElement(By.linkText("Download")).click();
try {
Thread.sleep(3000); //delay
}
catch (Exception e){
System.out.println(e);
driver.navigate().back();
driver.navigate().forward();

_______________________________________________________________________________________________

2.Verify The Functionality Of Successful Uploading File Using wget Utility



Steps to verify upload the file on particular website through Selenium Web Driver


1. Download the wget utility.
2. Create Driver for any Browser(Mozilla or Chrome)
3. Go to the URL in the code below and open the account for uploading the file. 
4. Use Selenium code to upload the file on box.

public class Uploadfile {
    private WebDriver driver;
    private String baseUrl;

    @Before
    public void setUp() {
        driver = new FirefoxDriver();
        baseUrl = "https://app.box.com/files";
    }

    @Test
    public void testUploadfile() {
        driver.get(baseUrl);

        driver.findElement(By.id("login")).sendKeys("<username>");
        driver.findElement(By.id("password")).sendKeys("<password>");
        driver.findElement(By.id("continue")).click();
        driver.findElement(By.id("upload_button")).click();
        driver.findElement(By.name("upload_element")).sendKeys("<Path of the file to be upload>");
        driver.findElement(By.id("popup_upload_button")).click();

    }

}


___________________________________________________________________________________

3.Verify The Functionality Of Successful Downloading file Using wget Utility



Steps to verify upload the file on particular website through Selenium Web Driver

1. Download the wget utility.
2. Create Driver for any Browser(Mozilla or Chrome)
3. Go to the URL in the code below and find xpath of the given link which is to be download. 
4. Create folder before running the code where downloaded file is to be saved.
4. Use Selenium code to upload the file on box.


public class Uploadfile {

    WebDriver driver;

    @Before
    public void setUp() {

        driver = new FirefoxDriver();
        driver.get("http://users.ugent.be/~bpuype/wget/");
    }

    @Test

    public void downloadfile() {


        WebElement anchortagDownload = driver.findElement(By.xpath("/html/body/blockquote/p[1]/a[2]"));

        String href = anchortagDownload.getAttribute("href");

        String wgetCommand;
        wgetCommand = "cmd /c C:\\DevTools\\wget.exe -P C:\\temp2" + " " + href;

        System.out.println(wgetCommand);

        try {


            Process exec = Runtime.getRuntime().exec(wgetCommand);

            BufferedReader reader = new BufferedReader(new InputStreamReader(exec.getErrorStream()));

            String line = null;
                    while((line = reader.readLine()) != null)

                    {
                        System.out.println(line);
                    }
               exec.waitFor();

        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    }

}


_______________________________________________________________________________________________

4.To Verify Presence of Image In Webpage By Using Selenium Webdriver

Steps to verify image is present on webpage.

1. Create Driver for any Browser(Mozilla or Chrome)
2. Go to the URL in the code below and locate the element by classname.
3. Use Selenium code to upload the file on box.

public class ImageHit {

    ChromeDriver driver;

    @Before
    public void setUp() {

        System.setProperty("webdriver.chrome.driver", "D:\\IntellijLib\\chromedriver.exe");
        driver = new ChromeDriver();
        driver.get("http://phenocare.com/");
    }

    @After
    public void tearDown()
    {
//        driver.quit();
    }

    @Test

    public void shouldoUnitTesting()
    {
        WebElement coaching = driver.findElement(By.linkText("Coaching"));
        coaching.click();

        WebElement element = driver.findElement(By.className("img-rounded"));
        element.click();
    }

}

_______________________________________________________________________________________________

5.To Check MouseOver Event With Particular Element on Webpage By Using Selenium Webdriver

 
public class ImageHit {
private FirefoxDriver driver;

@Before
public void setUp()
        {
        driver = new FirefoxDriver();
        driver.get("http://newtours.demoaut.com/");
        }

@Test
public void shouldDoUniTesting()
        {

        WebElement home = driver.findElement(By.linkText("Home"));
        WebElement trHome = driver.findElement(By.xpath("/html/body/div/table/tbody/tr/td[1]/table/tbody/tr/td/table/tbody/tr/td/table/tbody/tr[1]"));

        Actions actions =new Actions(driver);
        org.openqa.selenium.interactions.Action build = actions.moveToElement(home).build();

        System.out.println("Before Mouse Over" + trHome.getCssValue("background-color"));


        build.perform();

        System.out.println("After Mouse Over" + trHome.getCssValue("background-color"));

        }

        }


_______________________________________________________________________________________________

6.How To Perform Sequence Of Actions With Selenium Webdriver 

We want to perform multiple actions in once like, drag-and-drop, sliding, selecting multiple items.
Below example shows where we can use the Actions Interface of Selenium Webdriver.

public class demoMouseEvent {

private FirefoxDriver driver;

    @Before
    public void setUp()
    {
        driver = new FirefoxDriver();
        driver.get("http://newtours.demoaut.com/");
    }

    @Test
    public void shouldDoUniTesting()
    {

        WebElement userName = driver.findElement(By.name("userName"));


        Actions actions =new Actions(driver);
        actions.moveToElement(userName)
                .click()
                .keyDown(userName, Keys.SHIFT)
                .sendKeys("softedge")
                .keyUp(userName, Keys.SHIFT)
                .doubleClick(userName)
                .build().perform();

    }
}

___________________________________________________________________________________


We want to perform multiple actions in once, like: drag-and-drop, sliding, selecting multiple items. - See more at: http://selenium.polteq.com/en/perform-a-sequence-of-actions-with-selenium-webdriver/#sthash.OwiNTDJq.dpuf
We want to perform multiple actions in once, like: drag-and-drop, sliding, selecting multiple items. - See more at: http://selenium.polteq.com/en/perform-a-sequence-of-actions-with-selenium-webdriver/#sthash.OwiNTDJq.dpuf

Wednesday, 7 May 2014

Why Intellij IDEA is better than Eclipse?


There are "eternal" questions that have no single correct answer. E.g. what is better: Windows or Linux, Java or C#; who is stronger, IDEA or Eclipse......
One of such holywars is selection of the best Java IDE:






There is a lot of disputes on this topic discussing which of them has more plugins, shortkeys and so on. There is so many differences that it's difficult to decide what of them are the most important. As a result, people typically claim that both IDEs are equal in their capabilities, and choosing of one of them is a matter of taste.

 am going to show just one major differencebetween IDEA and Eclipse.


The main difference between IDEA and Eclipse

The main reason why IDEA is steeper is: IDEA feels context. That's what JetBrains employees mean when they name IDEA intelligent. What it really means? IDEA indexes the whole your project, analyses everything it has, and even builds the syntax tree.
Still not clear? Do not worry, it will become clear in the following examples.
This ability to understand the context is expressed in many, many ways, here are just a few.

1. Debugging

As a part of debugging process, we often want to evaluate some expression to see its value. In Eclipse you need to select this expression. It's important to exactly select the whole expression, otherwise Eclipse cannot evaluate it. Now you press Ctrl+Shift+I and see the value of expression.

With IDEA you don't need to select anything. You just put cursor at any place inside your expression (at method hasAttribute in given case) and press Alt+F8. IDEA understands which expression you probably need and shows a dialog window suggesting several possible variants for your expression. You can also edit and immediatelly evaluate the expression in this dialog. Very convenient! After trying this feature, you just cannot debug in Eclipse anymore. 
It turns out that both IDEs, in principle, allow you to do the same thing. But with IDEA it's much easier and faster. I'm serious, the difference is huge - it's just Heaven and Earth. In this small dialog window IDEA will provide autofilling, syntax highlighting and everything you need.

2. Autocomplete

Autocomplete is what distinguishes any IDE from the notepad. In this area feeling the context gives IDEA a qualitative advantage. For example, we started writing a line of code:
1.assertElement(By.id("errorMessage"), vi
and now we want to find what options do we have: what can start with letters "vi".
What IDEA does? Not waiting for any keystrokes, it immediatelly understands that method assertElement wants an Condition class instance as a second parameter, and there is a static variable in class Condition with name visible. And IDEA immediatelly suggests the only valid option: 
And what Eclipse does? Alas, it does not understand the context. It does not know that the cursor is located where the second parameter of the method assertElement should place. So when you press the sacred Ctrl + Space, Eclipse simply shows everything in Universe that begins with the letters "vi":

In a beautiful pop-up window we see a lot of pretty-highlighted well-documented useless information. :(

3. Refactoring

Professional programmers are able to be productive using refactorings provided by their IDE. All modern IDE offer a very impressive set of refactorings. 
For example, suppose we have a method assertErrorMessageIsHidden:
1.public void assertErrorMessageIsHidden() {
2.assertElement(By.id("errorMessage"), Condition.visible);
3.}

and we want the String "errorMessage" to come as a parameter to this method.

Let's start from IDEA. Put the cursor to any place inside the string "errorMessage", press Ctrl+Alt+P (meaning "parameter"), and IDEA suggests what expression we probably could extract to a parameter:
As soon as the expression "errorMessage" is selected, IDEA suggests several possible names for this parameter. 


Do not forget: select the entire expression "errorMessage" (always with quotes, or get a wild message "An expression must be select to activate this refactoring"), choose a refactoring "Introduce parameter" (from the menu, there is no hot key) and get about the same result. However, Eclipse doesn't suggest options for a parameter name,

 

Conclusion

If we are choosing a Java IDE then Intellij IDEA is definitely better than Eclipse. It's not just a matter of taste. IDEA is objectively better. It lets you to quickly and easily write and change the code, suggests appropriate names, finds the appropriate methods. It does not require you to exactly select the expressions, but guesses what you want to do and how you wanted to name it. IDEA anticipates and suggests.

Sunday, 30 March 2014

Selenium webdriver with maven

In today's post I would like to explain how we can quick start a selenium Java project using Maven. The term Maven may not be very familiar to many of the testers but widely used by Java developers. We can create a Selenium project without using Maven. Then why there is so much buzz about this magic word "Maven"? Let me explain how Maven can help testers to a great extend.

1) Dependency management - 

If you are not using maven you need to manage all the dependencies in your project manually. For example you are referring to selenium web driver version 2.31.0 in your project. So you may need to download the corresponding jar file before using it. Maven will do the same task for us. We just need to add the dependency in pom.xml file and rest maven will take care. Tomorrow if you want to use latest version of selenium just make the entry in pom.xml file, that's it.

2) Folder management - 

Maven creates a specific folder structure in the project one for keeping everything related to development and one for test. Since your base level folder structure is already created, we can easily customized this as per our need.

3) Plugin support - 

Maven provides lots of useful plugins which testers can use like for generating reports, creating documentations, configuring emails etc.

4) Integration with CI system - 

If you have requirements like integrating your tests in a CI system, maven can make your life easy.

Creating a simple java maven project for writing selenium test:
Installation:
Install maven eclipse plugin following the below steps:
Go to Help>Install New Software in eclipse IDE
Add "http://download.eclipse.org/technology/m2e/releases/1.0" in Work with
Follow the installation wizard.

Create a maven project:
1. File > New > Project
2. Select Maven project under Maven folder
3. Check the checkbox "Create simple project" and click on Next
4. Add the necessary details and click on Finish

After step 4 above, your sample maven project will be created.

Configure pom.xml file:
Open the pom.xml file. Default pom.xml file may look like this:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>test</groupId>
  <artifactId>test</artifactId>
  <version>0.0.1-SNAPSHOT</version>
</project>
Now we need to add the dependencies we need for selenium.

For example:
<!-- Add all your test dependency here-->
  <dependencies>
  <!-- selenium dependency -->
    <dependency>
      <groupId>org.seleniumhq.selenium</groupId>
      <artifactId>selenium-java</artifactId>
      <version>2.39.0</version>
    </dependency>

    <!-- testNG dependency -->
    <dependency>
      <groupId>org.testng</groupId>
      <artifactId>testng</artifactId>
      <version>6.1.1</version>
    </dependency>
       <dependencies>

And you are all set to try your first test using selenium webdriver and testNG.

Adding test classes:
You can add your test classes under src -> test -> java folder.
Do not forget to add "Test" word in your test class name. Maven picks only those test classes which has test word in name for running.

Running your test classes:
Once you add your test case, now you should be able to run the same as below:
1. Right click on the project folder.
2. Select "Run as" menu
3. Select "Maven test" menu

If everything goes well, you should be able to see your selenium tests running successfully. 

Select Language