Home Guide Test Automation Using JUnit Annotations and Selenium

Test Automation Using JUnit Annotations and Selenium

By Akshay Pai, Community Contributor -

JUnit is one of the leading frameworks for Java-based applications. In recent times, it has also been used to perform automation testing. Test automation here involves writing test cases with JUnit annotations along with Selenium Webdriver to simulate user interactions with a website’s UI. Using the automation capabilities of Selenium along with JUnit features makes life easier for automation testers, as this article will demonstrate.

JUnit And Its Capabilities

First released in 2002, the JUnit framework has been designed to write test cases for Java. When applications are being built for scale, Java is the most preferred programming language. Research on programming languages used to build high-traffic websites reveals that they are mostly based on Java. The graph below depicts the same:

Java is preferred language

Image Credit 

Since it is used to build scalable platforms, the testing framework should be reliable, feature-rich, and support various testing scenarios. JUnit 5 has been released recently, and the framework meets all the necessary criteria to become the go-to tool for automation testing.

An open-source framework, JUnit provides simple coding structures like annotations, a variety of assertions, and other provisions to build and maintain test cases. It also allows the grouping of multiple tests together to enable better maintenance of test suites.

Selenium And Its Capabilities

Selenium is an open-source automation tool used to test web applications on various browsers. It provides interfaces for developers so that they can emulate user behavior. It also supports a wide range of programming languages like PHP, Java, Python, and more.

UI test automation

Image Credit

At 29% market share, Selenium is a leading product for automated website testing. A few reasons for its dominant market share are :

  1. It has plugins for almost all the popular IDEs. This allows for easier adoption of Selenium automation.
  2. It supports a wide range of programming languages like Java, Python, .NET, PHP, Ruby, and more.
  3. Its open-source community has ensured that Selenium users have support for almost all the operating systems which ensures portability.
  4. It offers an entire testing suite consisting of a cloud Selenium Grid for distributed testing, web driver with multi-browser support, and more.

JUnit Selenium Testing with Annotations

The ideal automation suite comprises a robust testing framework, a leading test automation framework and a comprehensive set of real devices. Their individual strengths can be combined to build scalable multi-browser, multi-device test cases that deliver reliability to application development.

A JUnit test annotation is basically meta-data that JUnit provides to determine what action should be performed by a method. It allows developers to organize, group, and maintain test cases. Selenium allows integration with JUnit. To combine the two, one has to write Selenium test code within JUnit test classes.

This Selenium JUnit tutorial delves into JUnit annotations, Selenium test cases, and how they can be combined to achieve automated website testing.

Run Selenium Tests for Free

Fundamentals of JUnit Annotations

JUnit annotations are a major reason for the framework’s popularity. Annotations are fundamental markers that allow the framework to identify a specific task that needs to be executed.

Many tests can be combined into a single test class using this framework. All test cases might need a common initialization procedure to be executed before the test itself. There might be some clean-up(closing files, freeing up of resources, etc) required after a test is run. JUnit handles these “requirements” by making use of annotations. This way, the framework explicitly knows to distinguish between initialization tasks, the actual tests, and the post-execution tasks.

Let’s explore some of the most common annotations used to write a JUnit test case:

1. @BeforeClass and @AfterClass

The @BeforeClass annotation is run only once and specifically before anything else is run in the test class. This is extremely helpful for JUnit Selenium tests because the program must open a browser before running any of the Selenium tests. So, a method that initializes Selenium Webdriver and opens a browser can be annotated with the @BeforeClass annotation.

AfterClass, as the name might suggest, is the annotation used to execute tasks after all the tests have been completed. For example, @AfterClass will be used to close the browser and free that resource once all tests within the JUnit Selenium test class have been executed.

2. @Before and @After

These two annotations are meant to help automation developers write code that executes tasks before each test is run. When writing a Selenium test class, there might be a mandatory step that starts the test from a specific web page. In that case, one can use the @Before annotation so that the required webpage is opened and ready before any test is run.

Similarly, @After annotation is used to run tasks after the execution of each test. After every test, the test results might have to be sent to a logging service or a monitoring service. This can be achieved by using the @After annotation on the method which performs the task.

3. @Test

The @Test annotation is used to identify the actual test case. This is required as JUnit allows multiple tests to be grouped under a single test class. The test method is where assertions are done and the result is determined.

4. @RepeatedTest

Consider the following scenario. A web application is built to ensure caching does not occur due to highly dynamic data. So, each time the webpage is loaded, the cache must be empty. To automate the testing of this scenario, one has to run the same sequence multiple times.

With JUnit 5 annotations, the @RepeatedTest annotation was added. This can be used to run a given test any number of times. This annotation takes an integer attribute which tells JUnit to run the test a particular number of times.

Attributes to JUnit Annotations

Some JUnit annotations accept parameters called attributes that are used to provide more details to the test being run. Selenium requires these parameters to apply restrictions like timeout, number of times a test has to be executed, etc. Let’s look at an example and explore some of these annotation attributes.

@Test(timeout=5000)
@RepeatedTest(6)
public void test_search()
{ 
// code to search something using the search_bar
driver.findElement(By.id("search_bar")).sendKeys("Browserstack automation testing"); 
driver.findElement(By.name("search_btn")).click();

String first_result = driver.findElementByXPath("/html/body/result").getText(); 

assertEquals(first_result,”Testing and annotations”);
}

In the code snippet, there are two annotations @Test and @RepeatedTest being used. Each of them has been passed an attribute. The first annotation @Test has been set with the timeout (in milliseconds) attribute which tells Selenium to set the timeout to 5 seconds. Similarly, the second annotation @RepeatedTest takes in an integer which tells JUnit to run the test called “test_search” 6 times.

Passing attributes to some annotations is optional while for others, it’s mandatory. In the example above, the @Test annotation attribute is optional whereas the attribute to @RepeatedTest is mandatory.

JUnit Selenium Test: A Complete Example using Annotations

Have a look at a simple automation test that ties up everything discussed so far. This example intends to perform the following actions:

  • Submitting some details for the Sign-Up page
  • Testing successive page loads and checking if page reload succeeded
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
public class JUnitSeleniumTest {

public static RemoteWebDriver driver = null;
Public static DesiredCapabilities capabilities = null;

@Before
public void initializeSelenium() {
capabilities = new DesiredCapabilities()
capabilities.setCapability("browserName", "chrome");
capabilities.setCapability("version", "70.0");
capabilities.setCapability("platform", "win10");

driver = new RemoteWebDriver(new URL("https://google.com), capabilities);

}

@Test
public void signUp() {
driver.findElement(By.id("Name")).sendKeys("John Doe");
driver.findElement(By.id("Email")).sendKeys("johndoe@testemail.com");
driver.findElement(By.id("City")).sendKeys("Bangalore”);
driver.findElement(By.name("submit_btn")).click();

String result = driver.findElementByXPath("/html/body/response").getText();

assertEquals(result,”Sign-up Successful”);
}

@Test
@RepeatedTest(3)
public void reloadPage() {

driver = new RemoteWebDriver(new URL("https://google.com), capabilities);
assertEquals(homeUrl, "https://google.com/");
}

@AfterClass
public void cleanUp() {

driver.quit(); // close the browser
}
}

Let’s summarize the test class above. The test class consists of two tests, each annotated with @Test. The code starts by initializing Selenium Webdriver and annotating it with @Before on the initializeSelenium() method. This ensures that Selenium capabilities are initialized before running each test.

Run Selenium Tests on Real Device Cloud

Once initialization is complete, the two tests are run one after the other. The method cleanUp() is annotated with @AfterClass. This guarantees that the browser is closed only after both tests are executed completely.

This Selenium JUnit tutorial covers the most important constructs required to test websites automatically. Both these open-source automation tools are highly capable, and excellent tools for testers to achieve their goals.

BrowserStack Logo Run Selenium Tests on 2000+ Browsers & Devices Get Started Free