9g. WebDriver – Running WebDriver tests in JUnit4

Welcome to another interesting post in our WebDriver series! Its going to be a lot of fun today (may be less fun than eating your favorite chocolate).

Are you ready to throw your hat into the ring? If yes, then let’s get started!

Going forward, all our tests are going to be utilizing JUnit framework. Thus time to create a new package by right clicking on the project (which has selenium and junit set up) -> New -> Package. I have named my package as ‘com.blog.junitTests’.

Our next step is to create a class. Right click on the newly created package -> New -> Class. Give it a name, ‘FirstJunitTest.java’ and click on ‘Finish’. Your IDE should now look something similar to this,

JUnit implementation

Now that our class file is all ready for us to dive in, let us take up the same scenario as in “First test script – By launching Firefox” post.

  1. Open Firefox browser.
  2. Navigate to ‘https://www.google.com/’
  3. Assert the page title as ‘Google’.
  4. Display a message on the console based on the assertion result.
  5. Close the browser.

The reason for choosing the same scenario is that the code explanation remains the same. This will help you to clearly see the changes in the code with and without JUnit framework.

Sticky Note: This is not a JUnit tutorial. But basic explanation for an overall understanding will be provided wherever required. Refer http://junit.org/junit4/ for detailed and complete information.

The code is as follows,

package com.blog.junitTests;

import org.junit.*;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class FirstJunitTest {
	//Declaring variables
	private WebDriver driver; 
	private String baseUrl;
	private String pageTitle;
	private String expectedTitle;

	@Before
	public void setUp() {
		//Selenium version 3 beta releases require system property set up
		System.setProperty("webdriver.gecko.driver", 
                       "E:\\Selenium\\geckodriver-v0.10.0-win64\\geckodriver.exe");
		// Create a new instance for the class FirefoxDriver
		// that implements WebDriver interface
		driver = new FirefoxDriver();
		// Assign the URL to be invoked to a String variable
		baseUrl = "https://www.google.com";
		pageTitle = "";
		expectedTitle = "Google";
	}
	
	@Test
	public void testPageTitle(){
		// Open baseUrl in Firefox browser window
		driver.get(baseUrl);
		// Get the page title and assign to a String variable
		pageTitle = driver.getTitle();
		// Check if obtained page title matches with the expected title
		// and print the console output accordingly
		if (pageTitle.equals(expectedTitle)) {
			System.out.println("Hello World! Result is as expected.");
		} else {
			System.out.println("Hello World! Assertion failed!");
		}
	}
	
	 @After
	  public void tearDown() throws Exception{
		// Close the Firefox browser
		driver.quit();
	}
}

If this is compared to the code before JUnit was implemented, noticable changes would be,

  1. Annotations: @Before, @Test and @After
  2. Methods: setUp(), testPageTitle(), tearDown()
  3. Private variable declarations in the beginning of the class
  4. The same code being split into sections under the newly created methods

Does that make your vision blurry? Not to worry! Let us clear this mist immediately!!

Big Word Alert! Annotations: These convey a particular meaning to JUnit. They tell JUnit that the public void method that is attached to it should be,

@Test – treated and run as a test method.

@Before – run before each of the test methods specified. This is used for various purposes. Reading or assigning data, initializations or if multiple tests need similar objects to be created before they can be executed, it is best to specify under the method annotated with before.

@After – run after each test method is executed. Usually, commands related to environmental clean up are specified such as, closing open resources/database connections, deleting temporary data, releasing memory etc. Methods annotated with after are guaranteed to run even if @Before or @Test methods throw an exception.

Typing these annotations, a squiggly line appears below them. Upon hovering, the eclipse will suggest all possible quick fixes. Click on the first fix that suggests to import org.junit packages.

JUnit import packages

The methods under these three annotations are public and of return type void. Under junit.framework.TestCase class, we have setUp() and tearDown() methods. Best practice is to override these methods to write your initialization and cleanup code respectively. This not only will prevent memory leaks but also makes the code easier to read. JUnit calls setUp() method first, then the test method and finally tearDown() method. This happens for each test method attached to @Test.

To run the test,

Right click on the class -> Run As -> JUnit Test.

JUnit4 test execution

A new Firefox browser window opens and the test steps are executed as per the code. The result opens in JUnit View of Eclipse IDE showing a green bar for success and red bar for errors.

JUnit4 test success

Test case name is displayed. In case of errors, the stack trace is displayed. Shortcuts are available for re-running the tests, displaying only failures, viewing previous and next failed test etc. Below is a sample screenshot showing errors.

JUnit4 test error

We have reached the end of this post. It is now your turn to try out some scenarios implementing JUnit framework and giving a shout out in the comments section in case you face issues or have clarifications.

See you again in another post! Have a nice day!

Leave A Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.