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 -

What is JUnit? JUnit is a combination of two words – Java and Unit Testing. Given the popularity of Java in software applications, JUnit has gained in 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 apart from the rest of the testing frameworks available on the internet. Through JUnit, developers can run unit tests on each part of a software, before it goes to QA testers. Tests are run quickly and failed tests are listed in a separate section for easy debugging, making it the preferred choice of developers.

History of JUnit

Since its stable release in 2009, JUnit has garnered continuously positive reviews and has attracted many developers from the development community. According to Wikipedia, a survey conducted across 10,000 Java projects in 2013 found that JUnit was the most commonly included external library. JUnit has become a recommended standard for testing the projects written in Java language.

Besides manual testing, JUnit is preferred equally for automation testing on the projects. JUnit can also be used along with the Selenium WebDriver to automate tests for web applications. JUnit provides a unique way to write structured, short, and better test cases. JUnit makes use of annotations that allows the user to write 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 to teams. 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 take 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 tool is generally used for automating the process and repeating the test cases. Automation testing reduces human intervention and increases the success rate of the tests.

JUnit masters in writing the 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 post focuses on automation testing in JUnit with Selenium. Testing the website on different browsers is required to know about 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 works 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.

Run Selenium Test with JUnit for Free

Cross browser testing is the testing of a website on different browsers. The website can be published or unpublished. Every browser manufacturer tries to make its browser as unique and secure as possible to gain the people’s trust. Due to this, they do not implement all the features available in HTML, or they implement partial features. The 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 real devices. They can use assertions and annotations to make testing more robust. Let us 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 the 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.

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. JUnit is powerful and is continually evolving for better test case execution and better software results for the end-user. 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 Automate tool by BrowserStack, developers can conveniently run unit testing using Java with Selenium.

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

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