Thursday, December 19, 2013




What is JUnit Annotations?

JUnit is a unit testing framework for the Java programming language. JUnit has been important in the development of test-driven development. To execute Selenium WebDriver testing using JUnit we have to add JUnit annotations in your test.

Different JUnit Annotations:

We are using following most commonly used five annotations in our Selenium WebDriver test scripts:
1.     @Test
2.     @Before
3.     @After
4.     @BeforeClass
5.     @AfterClass
Test methods must be annotated by the @Test annotation. If the situation requires it, it is also possible to define a method to execute before or after of the test methods with the @Before or @After and @BeforeClass or @AfterClass annotations.
Let’s elaborate on these JUnit annotations here:

@Test

The annotation @Test identifies that a method is a test method. When it is mentioned as @Test before a test method, it tells JUnit framework that the following is a Test Method.

@Before

The @Before annotation is used to identify the method which is executed before executing the Test Method. This method can be used to set up the test environment.

@After

The @After annotation is method which is executed after executing the Test Method. This method can be used to do teardown i.e. deleting temporary data or setting up default values or cleaning up test environment etc.

@BeforeClass

The @BeforeClass method is used only once before start all tests. Basically this is used to perform time intensive activities, like connect to a database.

@AfterClass

The @AfterClass method is used only once after finish executing all tests. Basically this is used to perform clean-up activities, like disconnect from a database.
In upcoming article the we will use above listed JUnit annotations and create the Selenium WebDriver automation tests.

Different Testing Frameworks:

TestNG is a one of the more popular testing Framework used as alternative to JUnit testing Framework. It supports multiple advantages, powerful and unique features in the TestNG framework. As JUnit is comes with Eclipse so we don’t want to install separately. For TestNG testing framework we have to install this explicitly in Eclipse.
Many people’s are using JUnit testing Framework as it is come with Eclipse by default. It is simple & easy to use that why we have started with JUnit testing framework to execute Selenium WebDriver tests. Once time comes we will see how to install TestNG testing framework & how to execute test using this powerful framework.
In next Selenium Tutorial article, we are using above explained JUnit annotations and will explain “How to run a Selenium WebDriver Test with different JUnit Annotations” in this post. If you like this article then make sure to share it with your friends & please leave your questions/tips/suggestions in the comment section below and I’ll try to answer as many as I can.
If you are not regular reader of this website then highly recommends you to sign up for our free email newsletter!! Sign up just providing your email address below:

A. Record a Test case using in Selenium IDE
1) Launch FireFox & open to Selenium IDE by selecting “Tools > Selenium IDE” option.


In this blog post I will demonstrate how to write and run a simple test usingSelenium WebDriver.
This example is written in Java, but WebDriver supports many other programming languages (C#, Python and Ruby).

Download and install Chrome and chromedriver

Current versions of Firefox (> 16) seem to have issues when it comes to running these tests. You can try to debug and fix them, but another option is to use Chromeand chromedriver. Install Chrome. Download and unzip chromedriver in some location. Include the location of chromedriver in your path.

Download and install Eclipse

Download and install Eclipse. I chose Eclipse IDE for Java EE Developers, but other distributions should work fine, too.

Apache Maven

Apache Maven should come pre-installed with Mac OS X Snow Leopard and Lion. You can test if you have Maven installed by typing the following command in terminal:
mvn -version
The output should be similar to following:
...

Apache Maven 3.0.3 (r1075438; 2011-02-28 19:31:09+0200)

Maven home: /usr/share/maven

...
I do not cover installation of Maven in this blog, but there are plenty of tutorials available for all supported operating systems.

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

Create a new Maven project

·         In Eclipse: File -> New -> Other… -> Maven -> Maven project
·         Click: Next, Next, Next
·         Type in field Group Id:
com.yourcompany.selenium
·         Type in field Artifact Id:
yourclientprojectname
·         Click: Finish

Edit pom.xml

·         Update JUnit version to 4.9 and use the latest Maven repository release ofselenium-java:
·         <dependency>
·           <groupid>junit</groupid>
·           <artifactid>junit</artifactid>
·           <version>4.9</version>
·           <scope>test</scope>
</dependency>
·         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:

2) Make sure that Selenium IDE window is opened. In Selenium IDE the recording option is turned ON by-default.



3) Launch FireFox browser & enter URL as www.google.com same as shown below:
In Google Home page enter search keyword as Google and click on ”Google Search“ button as shown below:



4) Once the recording is done, you will able to see the recorded command in the command section. Turn off the recording option same as mentioned below. Upto this point you have successfully recorded script in Selenium IDE.



B. “Enable Experimental Features” from Selenium IDE options
1) Navigate to Options > Options
In Selenium IDE option, select “Enable Experimental Features” check box.



2) Navigate to Options > Format & select the “Java/ Junit 4 / WebDriver” option.

JavaJunitWebDriver1

3) JavaScript Application dialog will be display. Click on OK button.

Java/Junit/WebDriver2

4) Now you will able to see the Java code is displayed in Selenium IDE – Source tab. This code will be used for creating Selenium WebDriver code.

Java/Junit/WebDriver3

C. Create “firstPackage” under Selenium WebDriver project
1) In previous article we have learnt about “How to Create Project in Eclipse IDE?
Launch Eclipse IDE & open same project created in above step.
Right click on project name select option, New > Package.

Selenium WebDriver First Package

2) In New Java Package dialog enter Name as “firstPackage”

Eclipse new java package

3) Once you created the first package, ensure that it is added under “src” folder same as below:

Created first package in Eclipse

4) Right click on newly created package “firstPackage” select option, New > Class.

Create Class in Eclipse

5) In New Java Class dialog box enter class name in Name text box as “GoogleSearch” shown in below screenshot:

Eclipse Class Name

6) Once you created the “GoogleSearch” class, ensure that it is added under “firstPackage” folder same as below:

Eclipse Google Search Class

6) Now copy the Java/Junit4/WebDriver format converted code to from the previously recorded in Selenium IDE Source tab (Step A4).
Without deleting existing code paste the above recorded in Selenium IDE copied code below as shown below:

Selenium java/junit4/webdriver converted code

7) Upon pasting the code you will display some errors in the eclipse, don’t worry in next few steps we are resolving the all errors:

Selenium java/junit4/webdriver converted code error

8) Now in the code you experience that there are two packages, first is “package firstPackage;” & second is the “package com.example.tests;”.
The Class is allow to declare only one package but the copied code is added new package. So copied package is not present in the Eclipse IDE, so let’s comment out the package name “package com.example.tests;”.

Selenium code comment extra package

9) Once you resolve the more than one class declaration error then you will observe few warning messages as shown below:

Selenium code comment extra class

D. Remove the warning messages
1) We can see there are three warning messages shown in the below screen shot. To remove these warning messages, remove or comment the warning message lines.

Selenium WebDriver - comment warning message

2) Two methods called isElementPresent & closeAlertAndGetItsText methods are never used locally, so let’s comment out these two method sections:

Selenium code comment never used methods

3) One more warning message will get displayed once you commenting unwanted methods:

accept-next-alert

4) To resolve this problem comment out this line as this is never require while executing the code & click on Save All button shown below:

Save All Selenium WebDriver code

Download Code – Below is the final converted code from recorded Selenium IDE code. You can also copy below code & use directly.
01
package firstPackage;
02


03
//import java.util.regex.Pattern;
04
import java.util.concurrent.TimeUnit;

05
import org.junit.*;
06
import static org.junit.Assert.*;

07
//import static org.hamcrest.CoreMatchers.*;
08
import org.openqa.selenium.*;

09
import org.openqa.selenium.firefox.FirefoxDriver;
10
//import org.openqa.selenium.support.ui.Select;

11

12
public class GoogleSearch {

13
  private WebDriver driver;
14
  private String baseUrl;

15
  //private boolean acceptNextAlert = true;
16
  private StringBuffer verificationErrors = new StringBuffer();

17

18
  @Before

19
  public void setUp() throws Exception {
20
    driver = new FirefoxDriver();

21
    baseUrl = "https://www.google.com/";
22
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

23
  }
24


25
  @Test
26
  public void testGoogleSearch() throws Exception {

27
    driver.get(baseUrl + "/");
28
    driver.findElement(By.id("gbqfq")).clear();

29
    driver.findElement(By.id("gbqfq")).sendKeys("Google");
30
    driver.findElement(By.id("gbqfb")).click();

31
  }
32


33
  @After
34
  public void tearDown() throws Exception {

35
    driver.quit();
36
    String verificationErrorString = verificationErrors.toString();

37
    if (!"".equals(verificationErrorString)) {
38
      fail(verificationErrorString);

39
    }
40
  }

41
/*
42
  private boolean isElementPresent(By by) {

43
    try {
44
      driver.findElement(by);

45
      return true;
46
    } catch (NoSuchElementException e) {

47
      return false;
48
    }

49
  }
50


51
  private String closeAlertAndGetItsText() {
52
    try {

53
      Alert alert = driver.switchTo().alert();
54
      if (acceptNextAlert) {

55
        alert.accept();
56
      } else {

57
        alert.dismiss();
58
      }

59
      return alert.getText();
60
    } finally {

61
      acceptNextAlert = true;
62
    }

63
  }
64
  */

65
}

Here we have completed updating the Selenium WebDriver code in Eclipse. Before executing the script please make sure that Firefox browser is installed in your machine as we have used Firefox browser libraries. When you click on Run icon (Ctrl+F11) then your Selenium WebDriver code will be executed successfully.
Conclusion:
1) We have recorded a Test case using in Selenium IDE recording feature.
2) “Enable Experimental Features” from Selenium IDE options & converted generated HTML code to JUnit 4/Java/WebDriver format.
3) In Eclipse, created “firstPackage” & Class under Selenium WebDriver project & pasted above automated generated code in class.
4) One by one resolved all error & warning messages observed in code.


If you like this Selenium Automation article and you would also like to subscribe to our software testing email newsletter for software testing latest updates , please enter your email below:
Top of Form
Enter your email address:
Check email in your inbox for confirmation to get latest updates Software Testing for free.


How to use JUnit Annotations in Selenium WebDriver Automation Script
In our previous article we have learned basicIntroduction to JUnit Annotations used in your Selenium WebDriver Automation Test script. Now I want to give you brief idea about how to use these JUnit Annotations & what is actual use in the Selenium WebDriver code.
In Selenium WebDriver if you want to run test script using JUnit framework we have to add few JUnit Annotations in Selenium WebDriver Test script.
Below we are using few most commonly used JUnit annotations & execute our Selenium WebDriver Tests:
1.     @Before
2.     @Test
3.     @After
Let’s open previously created project in Eclipse IDE (click here to get How to create Selenium WebDriver Test using Selenium IDE? – Selenium Tutorial)
1) Once you open the above created Selenium WebDriver Test scriptand then check if have we used JUnit annotations in the code or not?
Junit Annotations Used In Selenium Webdriver Code
2) The highlighted part in above script is saying that we have used JUnit annotation in Selenium WebDriver code. In this script we have used @Before, @Test and @After annotations.
@Test
When we Run the script as JUnit then all the methods specified below@Test are executed using JUnit Test. As @Test JUnit annotation is specified before the testUntitled() method, this method will be executed when we run the “GoogleSearch” class using JUnit (i.e. Run As > JUnit Test)
Test Annotation Used In Selenium Webdriver
@Before
All the methods are defined in the @Before are executed first & then method which are defined in @Test are executed. The primary use of this annotation is used to set up the test environment which is needed for executing the test. You can in below screen shot we have used setup() method in @Before.
@After
All the methods are defined in the @Test annotation are executed first & then method which are defined in @After are executed. The primary use of this method is to do tear down i.e. deleting temporary data or setting up default values or cleaning up test environment etc.
Here @After annotation is specified before the ‘teardown()’ method. Hence this method will be executed by JUnit after executing all methods that are specified with @Test Annotation.
After Annotation Used In Selenium Webdriver
Run Selenium WebDriver Test Code without JUnit Annotaions:
Now let’s try to run Selenium WebDriver Test Code with commenting JUnit Annotaions & check if you are able execute test code as JUnit Test or not.
1. Comment all three Annotations line as shown in below screen shot. To comment line we have to add // before each line which we have to comment.
Comment Test Annotation Used In Selenium Webdriver
2. Run the Selenium WebDriver Test code with JUnit Test after commenting the annotations as shown below:
Junit Option Not Present
Now you understand if we are not using JUnit annotations in the Selenium WebDriver code then while running the code you cannot able to run the code as JUnit Test.
3. Now let’s uncomment annotations same as shown in below screen shot & check if you able to run the test using JUnit or not:
Uncomment Test Annotation Used In Selenium Webdriver
4. Have you notice that if we try to Run Selenium WebDriver code then the JUnit Test option is available as shown below:
Junit Option Present
So till now we have learned we can run the code using JUnit only if the JUnit annotations added in the code else Run As > JUnit Test option will not be available to Run the test.
Over to you
Have you ever tried executed your Selenium WebDriver script with & without JUnit Annotations? If no, then what are you waiting for, just follow above simple steps. If you have experience on Selenium WebDriver then can you please share experience in comments below.
If you enjoy reading this article please make sure to share it with your friends. Leave your questions/tips/suggestions in t

Bottom of Form



No comments:

Post a Comment

TestNG - Can i use the 2 different data providers to same @test methods in TestNG?

public Object [][] dp1 () { return new Object [][] { new Object [] { "a" , "b" }, new Obje...