How to execute a Selenium test in Java

53,767

Solution 1

A good way to run Selenium Java code in Eclipse is to run them as JUnit tests.

1. Create a Maven Project in your Eclipse.
If you haven't done this before, see:

2. Add the following dependencies to your pom.xml file:

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.7</version>
    <scope>test</scope>
</dependency>    
<dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>2.25.0</version>           
</dependency>    
<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-firefox-driver</artifactId>
    <version>2.33.0</version>
</dependency> 
<dependency><groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-server</artifactId>
    <version>2.25.0</version>    
</dependency>

3. Copy your exported Java file into the Maven Project.

4. Add the following imports to the file:

import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

5. Run the Java file as a JUnit test, like so:

Example from my Eclipse (Version is Kepler)

Solution 2

The previous answer are all legitimate. But to run directly from your eclipse you need do some modifications to your code. You dont need public void main to run a junit code. So Here are the steps to enable you to just copy over the code and paste it in eclipse and run as JUnit test:

  1. Install JUnit in eclipse->Help->eclipse market place-> search for JUnit and install it, restart eclipse.

  2. Create a project in eclipse and a new package, then create a new class with the same name as your selenium IDE exported code, delete everything except the package line.

  3. copy and paste the code from selenium IDE to that class, remove the package line.

  4. Right click in your code area and run as JUnit test.

Share:
53,767

Related videos on Youtube

Man Friday
Author by

Man Friday

Updated on January 26, 2020

Comments

  • Man Friday
    Man Friday over 4 years

    So I used Selenium IDE to create a test case for some automation I want done. I want to be able to create some looping/flow control for this case so I figured I would need to export it out of Selenium IDE to something like Java (I'm most familiar with Java). I exported to Java/JUnit4/Web Driver. I think trying to execute the java file through Eclipse would work best, although if someone knows something easier, let me know. Anyway, I have found NO GOOD EXPLANATION on how to execute this Java through Eclipse.

    Most things I read tell me to make sure my Build Path libraries includes the Selenium Standalone Server. Virtually all things I read tell me to use the Selenium Remote Control. However, I thought the RC was depreciated, and I am wondering if there is anyway to make it work with the more recent Web Driver stuff I downloaded from Selenium. Also, most things I read tell me I need to use public static void main(), which is a little awkward because I don't know how to alter the code the exported selenium gives me (obviously I can't just paste it all in the main method).

    If anyone could walk me through from exportation of Selenium to Java to executing the code, I will be forever in your debt.

    The code Selenium gives me: package com.example.tests;

    package com.rackspace;
    
    import java.util.concurrent.TimeUnit;
    
    import org.openqa.selenium.Alert;
    import org.openqa.selenium.By;
    import org.openqa.selenium.NoAlertPresentException;
    import org.openqa.selenium.NoSuchElementException;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.firefox.FirefoxDriver;
    import org.openqa.selenium.support.ui.Select;
    
    public class RackspaceContactAutomation {
       private WebDriver driver;
       private String baseUrl;
       private boolean acceptNextAlert = true;
       private StringBuffer verificationErrors = new StringBuffer();
    
       @Before
       public void setUp() throws Exception {
          driver = new FirefoxDriver();
          baseUrl = "https://cp.rackspace.com/Exchange/Mail/Contacts/List.aspx?selectedDomain=blahblahblah.com";
          driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
       }
    
       @Test
       public void testContactAutomationJava() throws Exception {
          driver.get(baseUrl + "/Exchange/Mail/Contacts/List.aspx?selectedDomain=blahblahblah.com");
          driver.findElement(By.linkText("Mr. Man")).click();
          driver.findElement(By.linkText("Contact Information")).click();
          new Select(driver.findElement(By.id("PhoneNumberType"))).selectByVisibleText("Mobile");
          driver.findElement(By.id("MobilePhone")).sendKeys("999-999-9999");
          new Select(driver.findElement(By.id("PhoneNumberType"))).selectByVisibleText("Fax");
          driver.findElement(By.id("Fax")).sendKeys("999-999-9999");
          driver.findElement(By.cssSelector("button.primary")).click();
       }
    
       @After
       public void tearDown() throws Exception {
          driver.quit();
          String verificationErrorString = verificationErrors.toString();
          if (!"".equals(verificationErrorString)) {
             fail(verificationErrorString);
          }
       }
    
       private boolean isElementPresent(By by) {
          try {
             driver.findElement(by);
             return true;
          } catch (NoSuchElementException e) {
             return false;
          }
       }
    
       private boolean isAlertPresent() {
          try {
             driver.switchTo().alert();
             return true;
          } catch (NoAlertPresentException e) {
             return false;
          }
       }
    
       private String closeAlertAndGetItsText() {
          try {
             Alert alert = driver.switchTo().alert();
             String alertText = alert.getText();
             if (acceptNextAlert) {
                alert.accept();
             } else {
                alert.dismiss();
             }
             return alertText;
          } finally {
             acceptNextAlert = true;
          }
       }
    }
    

    This gives me 4 errors (3 for the annotations, which I could just delete, and one for fail in the tearDown() method. It's not the errors I'm concerned about so much the how do I make this code actually execute?

    Thanks!

    • Arran
      Arran over 10 years
      It's a fully working Java code file. I am not so sure I understand what's complicated about it? Download and install JUnit into your project, and it'll take care of it.... docs such as this: code.google.com/p/selenium/wiki/GettingStarted ...simply use the main method to avoid the added extra 'bit' of a testing framework. That's all.
    • Arran
      Arran over 10 years
      Well, honestly, those errors are giving you a clue. A clue that shows you are missing one vital piece to the puzzle. You exported your tests as JUnit tests, but don't actually have JUnit imported. The answer below shows how to do that. So no, don't just ignore those errors. They are telling you whats wrong.
  • James Dunn
    James Dunn over 10 years
    Let me know if anything in my answer was unclear, I'll be happy to add explanations and update accordingly.
  • ddavison
    ddavison over 10 years
    You may want to clean up the bit that says "you need to run them as jUnit" Any unit-test framework will work. TestNG for example.
  • James Dunn
    James Dunn over 10 years
    Noted and changed. Thanks!
  • Man Friday
    Man Friday over 10 years
    @TJamesBoone thanks for the help! I am a total stranger to the idea of Maven anything. I don't want to waste all your time, but if you have a reliable link to how to make a maven project in eclipse that would be great. Even if it can best TestNG or other unit-test frameworks, I'll go with the least complicated
  • James Dunn
    James Dunn over 10 years
    @user2719370 I put two links in the answer, one for installing maven in eclipse and one for setting up the project. (The first link is another answer I made to a different question just now so I'd have something good to link to. If you find it helpful please upvote it!) Also, let me know if there's anything else, I'm glad to help.
  • Man Friday
    Man Friday over 10 years
    @TJamesBoone I will be sure to once I get enough reputation. So I'm trying to follow your instructions for install/integrating Maven with Eclipse. When I click on the Eclipse Marketplace I get a really weird error: "Cannot open Eclipse Marketplace Cannot install remote marketplace locations: Cannot complete request to marketplace.eclipse.org/catalogs/api/p: The document type declaration for root element type "html" must end with '>'."
  • James Dunn
    James Dunn over 10 years
    @user2719370 That's weird. I'll see what I can find. What version of Eclipse are you using?
  • Man Friday
    Man Friday over 10 years
    @TJamesBoone Kepler (Eclipse Standard 4.3). When I use a command prompt and type in mvn -version, it says mvn is not recognized
  • James Dunn
    James Dunn over 10 years
    @ManFriday Although that doesn't explain the weird error, if you are using Kepler then Maven should already be integrated with Eclipse. Have you tried making a Maven Project anyway without trying to install Maven first?
  • ddavison
    ddavison over 10 years
    If you have a test rpoject Man Friday, try right clicking it, Configure->Convert to Maven Project.. do you see this selection? if so, you're set. In my getting started project, clone that and you can see how maven works, and you will have a test right off the bat you can use.
  • Benjamin Gruenbaum
    Benjamin Gruenbaum about 9 years
    Please consider formatting your answer to a more readable format.

Related