Saturday, 13 September 2014

Creating and running a simple Selenium WebDriver test using Maven

Steps:

1. Download and install chromedriver & IEDriverServer
2. Download and install Java
3. Download and install Eclipse
4.
 Configure Apache Maven

Maven is a Java tool, so you must have Java installed in order to proceed.
a. JDK and JAVA_HOME
Make sure JDK is installed, and “JAVA_HOME” variable is added in Windows environment variable, and point to the JDK folder.
b. Download Apache Maven
Visit this Maven official website, choose a version and click on the download link, e.g apache-maven-3.2.3-bin.zip.
c. Extract It
Extract the downloaded zip file. In this case, we extracted to d driver and renamed the folder, e.g C:\maven.
Note That’s all, just folders and files, installation is NOT required on Windows.
d. Add MAVEN_HOME and PATH
Add a new M2_HOME variable to the Windows environment, and point it to your Maven folder.
Update PATH variable, append “Maven bin folder” path, so that you can run the Maven’s command everywher
e. Verification
Done, to verify it, in command prompt, type “mvn –version“.
C:\Documents and Settings\mkyong>mvn -version
Apache Maven 2.2.1 (r801777; 2009-08-07 03:16:01+0800)
Java version: 1.6.0_13
Java home: C:\Program Files\Java\jdk1.6.0_13\jre
Default locale: en_US, platform encoding: Cp1252
OS name: "windows xp" version: "5.1" arch: "x86" Family: "windows"

5. Install m2eclipse

Eclipse does not have integrated Maven support out of the box. To add the support, I am going to use Maven Integration (m2e).
  • In Eclipse: Help -> Install New Software…
  • Type the following URL in field Work with:http://download.eclipse.org/technology/m2e/releases
  • Click Add…
  • Give a name for the repository, such as:
    m2eclipse
  • Click OK
  • Select the checkbox Maven Integration for Eclipse
  • Click Next etc. to move forward and choose to restart Eclipse when prompted

6. Create a new project or Import Project using Maven


EX: pom.xml

  • Use the latest Maven repository release ofselenium-java:
    <modelVersion>4.0.0</modelVersion>
    <groupId>groupid</groupId>
    <artifactId>myautomation</artifactId>
    <version>1.0</version>
    
    <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
  • Add Selenium dependency:
    <dependency>
      <groupid>org.seleniumhq.selenium</groupid>
      <artifactid>selenium-java</artifactid>
      <version>2.25.0</version>
    </dependency>
  • Eclipse should detect the pom.xml changes automatically, build the project and download required dependencies
  • After the build is finished, there should be selenium*.jar files under Maven Dependencies under the Project Explorer pane

Cleaning up

  • Delete example class called AppTest.java under src/test/java

Create a new test class

  • Right-click over package com.yourcompany.selenium.yourclientprojectnameunder src/test/java and select New -> Class
  • Type in field Name:
    WhenSearchingForDrupalUsingGoogleTest
  • Click Finish

Implement the test class

Type or paste in the following code:
package com.yourcompany.selenium.yourclientprojectname;

import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

public class WhenSearchingForDrupalUsingGoogleTest {
  private String baseUrl;
  private WebDriver driver;
  private ScreenshotHelper screenshotHelper;
  
  @Before
  public void openBrowser() {
    baseUrl = System.getProperty("webdriver.base.url");
    driver = new ChromeDriver();
    driver.get(baseUrl);
    screenshotHelper = new ScreenshotHelper();
  }
  
  @After
  public void saveScreenshotAndCloseBrowser() throws IOException {
    screenshotHelper.saveScreenshot("screenshot.png");
    driver.quit();
  }
  
  @Test
  public void pageTitleAfterSearchShouldBeginWithDrupal() throws IOException {
    assertEquals("The page title should equal Google at the start of the test.", "Google", driver.getTitle());
    WebElement searchField = driver.findElement(By.name("q"));
    searchField.sendKeys("Drupal!");
    searchField.submit();
    assertTrue("The page title should start with the search string after the search.",
      (new WebDriverWait(driver, 10)).until(new ExpectedCondition() {
        public Boolean apply(WebDriver d) {
          return d.getTitle().toLowerCase().startsWith("drupal!");
        }
      })
    );
  }
  
  private class ScreenshotHelper {
  
    public void saveScreenshot(String screenshotFileName) throws IOException {
      File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
      FileUtils.copyFile(screenshot, new File(screenshotFileName));
    }
  }
}

Run the test

  • Using terminal, navigate to your project folder under your workspace folder
  • Type in command:
    mvn clean test -Dwebdriver.base.url=http://www.google.com
  • You should see compilation messages and finally something resembling the following:
-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.yourcompany.selenium.yourclientprojectname.WhenSearchingForDrupalUsingGoogleTest...
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 3.95 sec

Results :
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
If everything went well, there should exist a file named screenshot.png at the root of your project folder. If there were errors, you can go and find more information under target/surefire-reports.

No comments:

Post a Comment