JUnit Testing Tutorial: JUnit in Java
By Harish Rajora, Community Contributor and Pradeep Krishnakumar - February 10, 2023
JUnit combines two words – Java and Unit Testing. Given the popularity of Java in software applications, JUnit has gained serious popularity. Let’s get deeper into the details in the following JUnit tutorial.
What is JUnit Framework?
Over the years, the JUnit framework has helped develop 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 separately 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 create different test scripts for various purposes using several methods.
Importance/Benefits of JUnit Testing Framework
While JUnit is a primitive way to test Java-based projects, it provides many advantages.
Following are a few benefits of using the 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 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 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, which are most efficient when they fail. So, JUnit helps in the TDD build of the software.
Also Read: JUnit Vs TestNG
Getting Started with JUnit Automation Testing
Automation testing refers to the process of testing software through automated processes. A dedicated tool is used for replicating user actions and repeating test cases. Automation testing reduces human intervention and increases tests’ accuracy and success rate.
- 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 more reliable results.
- Since the error margin is significantly less in automation testing, talking about JUnit without considering 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 the way the manufacturer wants.
For example, the placeholder attribute was unavailable 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 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.
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 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 indicates 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 } }
Like the @BeforeClass, @AfterClass runs once when all the tests are executed. So, we have briefed ourselves with the annotations, and now let us use them along with 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 execution of the test are 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("userid"); //Sending ID driver.findElement(By.id("pwd")).sendKeys("userpassword"); // 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("userid"); driver.findElement(By.id("pwd")).sendKeys("userpassword"); //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.
Final Thoughts
- JUnit testing in Java is the most preferred method as it is robust and continually evolving for better test case execution. It has become a preferred choice for Test-driven development cycle.
- Selenium is a convenient tool for 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, no matter how well crafted, tests cannot be regarded as conclusive if they are not run on real devices. Emulators and simulators cannot replicate end-user conditions properly, especially regarding weak networks and low battery. Run tests directly on a real device cloud to compensate for these inadequacies.
- 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.
Read More: JUnit 4 Tutorial: Run Test cases in JUnit 5