• Jobs
  • About
  • A simple Selenium 2 example March 1, 2011

    Introduction

    As mentioned in the Introduction to Selenium post, Selenium is a great test automation tool for driving browsers for testing web applications. Selenium contributors are now coming out with Selenium 2 which has some new, more expressive APIs, along with backward compatibility. This post describes:

    • Downloading and setting up Selenium 2
    • Running a simple test written using Selenium 2’s new API in Java.

    The assumption here is that you have an environment setup similar to the one defined in the Creating your Java project workspace post.

    Downloading and setting up Selenium 2

    At this time, Selenium 2 is at beta 2. Follow these steps to add Selenium in your project.

    1. Download Selenium 2 zip file in your download directory … on unix lets assume its located at ~/Downloads
    2. Unzip the file by doing
      unzip selenium-java-2.*.zip
    3. You will notice several jar files in the exploded folder. You could copy all the jar files, but for this example, all you need are commons-exec-1.1.jar, guava-11.0.1.jar, httpclient-4.1.2.jar, json-20080701.jar, junit-dep-4.10.jar, commons-logging-1.1.1.jar, hamcrest-all-1.1.jar, httpcore-4.1.3.jar, jsoup-1.6.1.jar, selenium-java-2.*.0.jar. Copy these to your project lib (testautomation/lib/.) directory.

    Writing your first test in Java

    Unlike previous versions of Selenium, starting the selenium server is optional. In this case, we are not going to start the selenium server.

    Let us start with creating a class org.qaautomation.examples.GoogleSearch.java

    package net.qaautomation.examples;
    
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.firefox.FirefoxDriver;
    import org.openqa.selenium.support.ui.ExpectedCondition;
    import org.openqa.selenium.support.ui.Wait;
    import org.openqa.selenium.support.ui.WebDriverWait;
    
    /**
     * Search Google example.
     *
     * @author Rahul
     */
    public class GoogleSearch {
        static WebDriver driver;
        static Wait<WebDriver> wait;
    
        public static void main(String[] args) {
            driver = new FirefoxDriver();
            wait = new WebDriverWait(driver, 30);
            driver.get("http://www.google.com/");
    
            boolean result;
            try {
                result = firstPageContainsQAANet();
            } catch(Exception e) {
                e.printStackTrace();
                result = false;
            } finally {
                driver.close();
            }
    
            System.out.println("Test " + (result? "passed." : "failed."));
            if (!result) {
                System.exit(1);
            }
        }
    
        private static boolean firstPageContainsQAANet() {
            //type search query
            driver.findElement(By.name("q")).sendKeys("qa automation\n");
    
            // click search
            driver.findElement(By.name("btnG")).click();
    
            // Wait for search to complete
            wait.until(new ExpectedCondition<Boolean>() {
                public Boolean apply(WebDriver webDriver) {
                    System.out.println("Searching ...");
                    return webDriver.findElement(By.id("resultStats")) != null;
                }
            });
    
            // Look for QAAutomation.net in the results
            return driver.findElement(By.tagName("body")).getText().contains("qaautomation.net");
        }
    }
    

    Do
    ant build
    and
    ant run-example -Dexample=GoogleSearch
    to run the example. You will notice a firefox window open, do the search and end with the test passing if qaautomation.net shows up as one of the search results.

    Further reading

    Once you have seen a simple example of Selenium 2 using WebDriver, you might want to get more details about building tests using different browser types, different element locating strategies, ways you can simulate keyboard and mouse actions etc. For all of this and more check out the Selenium 2 User Guide.

     

    Posted by Rahul Poonekar in : Selenium

    29 responses to “A simple Selenium 2 example”

    1. Ramdas Singh says:

      Hi Rahul,

      I work as a software test engineer for SRA International. As a volunteer I teach a course on “Test Automation Using Selenium” for SRA University (a small unit of SRA). During the fall of 2010 I taught the course using Selenium 1. But during the spring of 2011 I have planned to teach the course using Selenium 2. I tested your code and it worked. If you come to Virginia, you can stay with us if you like to.

      Thanks for putting the example on the web.

      Regards,

      Ramdas Singh

    2. I have been playing with Eclipse IDE and java Webdriver for only 3 hours and tried this example which worked a treat. thanks

    3. Naresh says:

      This helped alot to explore….thanks…

    4. David says:

      Very different from Selenium 1. I like the expressive API.

      It would be interesting to see a JUnit example (showing typical use of assertions).

    5. rajat says:

      hi ,
      i had spent 15 hours googling for a code which would work , but this was a treat , thanks a lot . i had lost hope , but this was a wonder 🙂

    6. Björn says:

      Great work, really helpful. I was about to give up on selenium 2. But this article really helped

    7. abhishek says:

      It was just awesome..more than expected for me.I was going for nothing when i suddenly came across with this example .I used it with eclipse and the results were not lesser than a reward to me…thanks a lot….!!!!

    8. San says:

      Hi All,
      I am new to Selenium can you please explain me in detail to run the above google example through Selenium2.

      Thanks in advance.

    9. zim says:

      Your example is awesome.. But without IDE anyone would be crazy to use this.. why not stick with html unit or webtest if you have to manually program so much..

    10. Soonick says:

      Hello,

      I am trying to tun this example but I am getting an error:

      BUILD FAILED
      /home/soonick/Web/tests/selenium/build.xml:41: Could not find net.qaautomation.examples.GoogleSearch. Make sure you have it in your classpath

      I followed your post: Creating your Java project workspace post. and my build.xml file is exactly the same as the one in your post.

      I created the file org.qaautomation.examples.GoogleSearch.java with the content from this example and placed it in my classes folder.

      Please let me know if you have any idea of what is causing the problem.

      Thanks

    11. Soonick says:

      Hello,

      I found what I was doing wrong. I needed to save the file from this post in my src folder, not in my class folder. Also the name needs to be GoogleSearch.java

      Thanks for your tutorial

    12. naveen reddy says:

      Hi really a great post on selenium..
      I am new to Selenium can you please elaborate on how to execute the above test in step by step manner.

      Thanks
      Naveen

    13. Rahul Poonekar says:

      Naveen,

      If you look at the Selenium 2 User Guide, it will deconstruct this example over several sections.

      Thanks

    14. MKane says:

      Hi please hlp me. I tried your code upon but it doesn’t work. I become an access denied and the google page couldn’t be opened.
      I thing may be I need to specify a proxy to open my given url. But I don’t know exactely. Please help me.

    15. raghu says:

      A good starting point for me. Thank you

    16. Ravibabu Polagani says:

      I am new to Selenium can you please explain me in detail to run the above google example through Selenium.

      Thanks
      Ravi Polagani

    17. prasanta says:

      thnaks it work for me too

    18. Nallasivam says:

      Ya its work fine for me also, but i want to know the good tool which will be helpful to locate the elements and could you please share more valuable examples on WebDriver using Java

    19. shaker says:

      Is there a way to copy the source code for pasting into Eclipse without getting the line numbers? Thanks.

    20. shaker says:

      Never mind. I just the View Source button. Thanks for this site.

    21. Manish B says:

      I am getting below error while running this code

      Exception in thread “main” java.lang.NoClassDefFoundError: com/google/common/base/Function
      at com.selenium.example.FirstTest.main(FirstTest.java:17)
      Caused by: java.lang.ClassNotFoundException: com.google.common.base.Function
      at java.net.URLClassLoader$1.run(Unknown Source)
      at java.net.URLClassLoader$1.run(Unknown Source)
      at java.security.AccessController.doPrivileged(Native Method)
      at java.net.URLClassLoader.findClass(Unknown Source)
      at java.lang.ClassLoader.loadClass(Unknown Source)
      at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
      at java.lang.ClassLoader.loadClass(Unknown Source)
      … 1 more

    22. vinothkumar says:

      Hi,I am new to selenium.Am tried for gmail application in some of the issue would occured.For reason xpath can be changed first time this script can be run after five minutes that same script couldn’t be ran.How can be handled this kind of issue.Anybody can tell me plz

    23. sneha says:

      hi,
      its working fine.

      And i need to ask that how actually automation testing is happening?its just navigating through all the fields as you provide in the code.
      In manual we used to test its working fine or not with different validations like that is it possible to automate by drawing data from table i.e.excel sheet containing different validation values..?

      Please help me to get my doubt clear

      Thank you

    24. Surendra Singh Tomar says:

      great example :

      Suggestion is if you face problem with firefox driver there is an alternate solution switch to crome
      example : System.setProperty(“webdriver.chrome.driver”, “F://selenium/chromedriver.exe”);
      WebDriver driver = new ChromeDriver();
      driver.get(“http://www.google.com”);

      Cheers

    25. pennysap says:

      hi,
      I am new to Selenium and also new to java coding.
      Can you please tell me coding for already selected or active link of table and print data of table for already selected link then go to next link automatically?

    26. Naddo says:

      Hi I am getting following error.
      org.openqa.selenium.NoSuchElementException: Unable to locate element: {“method”:”name”,”selector”:”q”}

    27. neelima says:

      private static final WebElement FirefoxDriver = null
      why this code is used

    28. Gopal says:

      Hi Team-
      I an beginner to Selenium. If some one send me the sample examples, that would be great.

    29. Sumit says:

      Is there is any way of testing two forms of having same url like abcd.com and in abcd.com we have register button after clicking on register button(with email textbox) after validating email 1 another form will open that consists registration details like name , last name , etc … i dont know hoe to test such scenario

    Leave a Reply

    Your email address will not be published. Required fields are marked *