App & Browser Testing Made Easy

Give your users a seamless experience by testing on 3000+ real devices and browsers. Don't compromise with emulators and simulators

Home Guide JUnit Testing Framework : Get Started for Automation Testing with Selenium

JUnit Testing Framework : Get Started for Automation Testing with Selenium

By Harish Rajora, Community Contributor and Pradeep Krishnakumar, Manager -

Table of Contents

What is JUnit?

JUnit combines two words – Java and Unit Testing. Given the popularity of Java in software applications, JUnit has gained serious popularity.

Over the years, JUnit has helped in the development of a test-driven methodology. The GUI available in JUnit for writing repeatable and manageable test cases makes it stand out from other testing frameworks on the internet. Through JUnit, developers can run unit tests on each software component before it goes to testers. Tests are run quickly and failed tests are listed in a separate section for easy debugging.

Besides manual testing, JUnit is preferred equally for automation testing. It can also be used along with the Selenium WebDriver to automate tests for web applications. It provides a unique way to write structured, short, and better test cases. JUnit uses annotations to allow the creation of different test scripts for various purposes using several methods.

Why is JUnit Testing Framework Important?

While JUnit is a primitive way to test Java-based projects, it provides many advantages. Following are a few benefits of using JUnit Testing Framework:

  • Open Source: JUnit is an open-source testing framework. Hence, a broader community can contribute to the software. That leads to better and faster development from developers across the world.
  • Early bug-finder: JUnit finds the bug early in code as compared to other test frameworks. When a bug is found, it is indicated in a separate section until it is resolved. This helps drive focus on debugging.
  • Best for Test-Driven Development (TDD) Environment: To push the least number of bugs to QA teams, many engineering teams pick a test-driven development cycle. Developers first perform tests, and issues are resolved, before taking the build for QA testing. JUnit uses assertions in the tests, and assertions are most efficient when they fail. So, JUnit helps in the TDD build of the software.

Getting Started with Automation Testing using JUnit

Automation testing refers to the process of testing the software through automated processes. A dedicated tool is used for replicating user action and repeating test cases. Automation testing reduces human intervention and increases accuracy and success rate of tests.

JUnit is best at creating repeatable test cases. If there is a need to run a test in JUnit 100 times, one doesn’t need to write it 100 times or not even execute it manually 100 times. This process is automated. Automation testing is usually preferred over manual testing because of faster and reliable results. Since the error margin is very less in automation testing, talking about JUnit without taking into consideration automation testing won’t be enough.

This article focuses on automation testing in JUnit with Selenium. But before proceeding, bear in mind a site should be tested on different browsers to identify any anomaly or glitch beforehand and to optimize the code and website accordingly. Since every browser is different and renders the website differently, the elements that make up the website work in a way that the manufacturer wants.

For example, the placeholder attribute was not available on Internet Explorer 6 earlier. However, it was available in other browsers. There are many such issues, and a developer needs to take care of them. These issues are cross-browser issues, and testing it is known as cross-browser testing.

This is why cross browser testing is essential in any testing pipeline. Every browser manufacturer tries to make their browser as unique and secure as possible. Due to this, they do not implement all the features available in HTML, or they implement partial features. A website on one browser may lack some features on the other due to these reasons. A developer needs to take care of this.

For this, teams adopt cloud-based online testing platforms like BrowserStack. Teams can run Selenium test suites on a real device cloud of 3000+ real browsers and devices. Automated Selenium testing becomes a breeze in real user conditions. Simply sign up for free, select the browser-device duo you want to test on, and start testing. Additionally, BrowserStack offers robust support for running Selenium tests with JUnit.

Try Selenium Testing with JUnit

Testers can use assertions and annotations to make testing with JUnit more robust. Let’s get familiar with the assertions and annotations used in JUnit for testing.

Annotations used in JUnit Testing

JUnit is made up of assertions and annotations that are implemented in the code while testing. Annotations are the indicators in JUnit that tell the compiler what to do with the code following the annotation. For example, an annotation of @Test in JUnit indicates that the code following this annotation has the testing code in it.

JUnit annotations are very simple. Below listed are a few annotations:

  • @Before: Before annotation is used to run code before every test in JUnit. This is used to initialize methods before the test executions. This can be creating the entry in the database or initializing variables or other. As an example:
public class BrowserTest{
@Before
public void beforeTest(){
//Code to run before test
}
}
  • @Test: Test annotation contains the code for the initial test. It executes after the @Before code has been executed (if you have placed it).
public class BrowserTest{
@Before
public void beforeTest(){
// Code to run before the test
}

@Test
public void testingCode(){
//code for testing
}
}
  • @After: After annotation is used to indicate the code that has to run after the testing code has been executed. This is usually used to destroy the variables and free up memory.
public class BrowserTest{
@Before
public void beforeTest(){
// Code to run before the test
}

@Test
public void testingCode(){
//code for testing
}

@After
public void afterTest(){

//code after testing
}
}
  • @BeforeClass: The BeforeClass annotation indicates the code that has to run before running all the tests. This code runs once and must be static.
public class BrowserTest{

@BeforeClass
public static void beforeClassTest(){
// Code to run once before the test.
}

@Before
public void beforeTest(){
// Code to run before the test
}

@Test
public void testingCode(){
//code for testing
}

@After
public void afterTest(){

// Code after testing
}
}

@Beforeclass Code runs just once while the @Before Code runs every time the test needs to run. If the test has to run 10 times, @Before gets executed ten times while the @BeforeClass runs only once.

  • @AfterClass: AfterClass annotation is used to indicate that the code following this annotation is executed after all the tests have been executed.
public class BrowserTest{

@BeforeClass
public static void beforeClassTest(){
// Code to run once before the test.
}

@Before
public void beforeTest(){
// Code to run before the test
}

@Test
public void testingCode(){
//code for testing
}

@After
public void afterTest(){

//code after testing
}
@AfterClass
public static void afterClassTest(){
//Code to run after the test
}
}

Similar to the @BeforeClass, @AfterClass also runs just once when all the tests are executed. So, we have briefed ourselves with the annotations, now let us use them along with the Selenium to test our code.

Now that you know about JUnit assertions, try running them on real browsers and see how Selenium and JUnit tests work for you. Have a go at our Cloud Selenium Grid and play around with real device and browser testing. 

How to perform JUnit Testing with Selenium

This section focuses on testing the code with Selenium and JUnit. This type of testing comes under automation testing since the workflow, and the execution of the test is automated. Selenium and JUnit can be combined to make a powerful test combination to test websites. We will test on BrowserStack to check for the login functionality using valid and invalid credentials.

import java.util.concurrent.TimeUnit;

import org.junit.AfterClass; //Importing all the JUnit and Selenium classes
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class FirstTest {
private static FirefoxDriver driver;
WebElement element;

@BeforeClass
public static void openBrowser(){
driver = new FirefoxDriver(); //Initialising the browser driver
}

@Test
public void validUserCredentials(){ //To test successful login

System.out.println("This is the test code " + new Object(){}.getClass().getEnclosingMethod().getName());
driver.get("https://www.browserstack.com");
driver.findElement(By.xpath(".//*[@id='account']/a")).click();
driver.findElement(By.id("log")).sendKeys("harish@browserstack.com"); //Sending ID
driver.findElement(By.id("pwd")).sendKeys("harish123"); // Sending PWD
driver.findElement(By.id("login")).click();
try{
element = driver.findElement (By.xpath(".//*[@id='account_logout']/a"));
}catch (Exception e){
}
Assert.assertNotNull(element); //Checking the element presence
System.out.println("Test End " + new Object(){}.getClass().getEnclosingMethod().getName());
}

@Test
public void WrongUserCredentials()
{
System.out.println("Starting test " + new Object(){}.getClass().getEnclosingMethod().getName());
driver.get("https://www.browserstack.com");
driver.findElement(By.xpath(".//*[@id='account']/a")).click();
driver.findElement(By.id("log")).sendKeys("harishrajora@browserstack.com");
driver.findElement(By.id("pwd")).sendKeys("harish234"); //Entering wrong pwd
driver.findElement(By.id("login")).click();
try{
element = driver.findElement (By.xpath(".//*[@id='account_logout']/a"));
}catch (Exception e){
}
Assert.assertNotNull(element);
System.out.println("Ending test " + new Object(){}.getClass().getEnclosingMethod().getName());
}

@AfterClass
public static void closeBrowser(){
driver.quit(); //Closing the driver once the tests are executed
}
}

The above test is just a sample test to show how JUnit and Selenium work together.

Test Run Selenium with JUnit for Free

Final Thoughts

  • JUnit testing is the most preferred testing method if the project has been developed in Java. It is powerful and continually evolving for better test case execution. It has become a preferred choice for Test-driven development cycle.
  • Selenium is a convenient tool when it comes to automated web testing and using it along with JUnit is even more beneficial. JUnit supports multiple assertions and annotations. Using BrowserStack Automate, developers can conveniently run unit testing using Java with Selenium.
  • However, tests, no matter how well crafted, cannot be regarded as conclusive if they are not run on real devices. Emulators and simulators cannot replicate end-user conditions properly, especially when it comes to aspects like weak networks and low battery. To compensate for these inadequacies, run tests directly on a real device cloud.
  • Use parallel testing. Instead of running tests sequentially, parallel testing allows for simultaneous test execution. For example, it enables QAs to run the same test on multiple device-browser combinations simultaneously, significantly reducing time and effort.

Additionally, read this detailed step-by-step tutorial on how to run your first test using Selenium and Java.

Tags
Automation Testing Selenium Testing Tools

Featured Articles

Selenium with Java : Getting Started to Run Automated Tests

Selenium RemoteWebDriver : Difference between WebDriver and RemoteWebDriver

Selenium vs Cucumber: Core Differences