Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is JUnit
3.
Setting up the Environment
4.
Writing Tests in JUnit
4.1.
Program  
4.2.
Creating Test File
4.3.
Template Test Code
4.4.
Empty Test Code
4.5.
Test Code
4.6.
Understanding Test Code
5.
FAQs
6.
Key Takeaways
Last Updated: Mar 27, 2024

JUnit Introduction with Eclipse

Author Aditya Anand
1 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

Welcome readers! In this blog, we will learn about JUnit, one of the essential unit testing frameworks for the Java programming language. We will first get the basic overview of what JUnit is and what it does. We will set up an Eclipse environment, and then we will write and understand an example unit test in JUnit.

Let's get started, and I hope you learn a lot from this tutorial.

What is JUnit

JUnit is a unit testing open-source framework for the Java programming language. Java Developers use this framework to write and execute automated tests.

JUnit has set a benchmark when it comes to testing Java applications. Since JUnit is compatible with almost all IDE's, organisations worldwide have adopted it to perform unit testing in the Java Programming Language.

Erich Gamma and Kent Beck initially developed it. It is an instance of xUnit architecture, and It plays a crucial role in test-driven development. 

JUnit, NUnit, CppUnit, DbUnit, PHPUnit, HTTPUnit, etc. such frameworks for unit testing are commonly referred to as “xUnits.”

JUnit is linked as a JAR at compile-time. The latest version of the framework, JUnit 5, resides under package org.junit.jupiter. Previous versions JUnit 4 and JUnit 3 were under packages org.junit and junit.framework, respectively.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Setting up the Environment

We will first set up an environment to perform unit testing using JUnit. Since JUnit is a Java programming language testing framework, we will be using Eclipse IDE.

So let’s start by downloading Eclipse from Eclipse Downloads | The Eclipse Foundation if you don’t have Eclipse already installed on your computer.

  

 

Click on download and then install it on your computer.

Now we will create a new Maven project in which we will write some code and then unit test those using JUnit.

Click on Create a Maven project to create a new maven project.

        

 

A pop will appear like this. Click on the checkbox. Create a simple project to skip archetype selection since we will be creating a simple project. Click next.

    

Something like this will appear, provide group id and artifact id, and click finish.

We have successfully created our new maven project. The folder structure will look like the image below, we have src/main/java where we will be writing the main code, and we also have src/test/java where we will be writing all our unit testing code.

This is an optimal structure since our main files and test files are in separate folders.

Writing Tests in JUnit

Before writing unit tests using JUnit, we must write some code to test. So I will make an addTwoNumbersMethod class inside which I will define an add method that simply adds two integers and returns the result.

Program  

package com.aditya04848.junit.helper;

public class addTwoNumbersMethod {
   
    public static int add(int Number1,int Number2){
        int Sum;
        Sum = Number1 + Number2;
        return Sum;
    }
}

Our code is ready to be tested, so let’s create a JUnit test case. 

Creating Test File

To do that Right-click -> new -> other

 

This popup will appear. 

Search JUnit and select JUnit test case and click next.

Provide package name, and typically the package is taken the same as the class name it is testing.

Browse for the class under test, the popup shown below will appear, search the name of the class and select it, then click finish.

On clicking finish, this popup will appear asking to add JUnit to the build path. Ideally, we should add to pom.xml but for simplicity, let’s select add JUnit 4 library to the build path, click ok.

The following test code will be created automatically as a template test file.

Template Test Code

package com.aditya04848.junit.helper;
import static org.junit.Assert.*;

public class addTwoNumbersMethodTest {

    @Test
    public void test() {
    fail('Not yet implementaed');
    }
} 

Let's actually run this and see what happens. To run the test Right-click -> Run as -> Junit test.

And we got a failure trance because of the fail() method. The red bar below indicates that our test has failed.

output

Now Let's remove the fail() method like shown in the picture below and then run again.

Empty Test Code

package com.aditya04848.junit.helper;
import static org.junit.Assert.*;

public class addTwoNumbersMethodTest {

    @Test
    public void test() {
       
    }
}

output

This time our test passed because in Junit if the test doesn’t fail, it is considered a pass.

Now let's write our actual testing code. After that, we will understand each and every line and its significance.

Test Code

package com.aditya04848.junit.helper;

import static org.junit.Assert.*;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class addTwoNumberMethodTest {

    addTwoNumbersMethod obj;
   
    @Before
    public void setup() {
        obj = new addTwoNumbersMethod();
    }
   
    @Test
    public void addTestCase1() {
        assertEquals(10, obj.add(5,5));
    }
   
    @Test
    public void addTestCase2() {
        assertEquals(10, obj.add(6,4));
    }
   
    @After
    public void tearDown( ) {
        System.out.println("test completed");
    }
}

Let’s first try to run and check if it is working.

And voila, all two of the tests passed.

Output

 

Let's now understand everything in the code.

Understanding Test Code

Annotations: JUnit Annotations are a special form of syntactic meta-data that can be added to Java source code for better code readability and structure.

@Test annotation defines that the below method is a test method.

@Before / @After annotation defines that the method written below will be executed before and after every @Test method. This is overkill in our project but in more complex projects,

we need some code to be executed before and after each test, so instead of writing them in each test method, Junit provides these annotations to help keep our testing code dry.

Junit provides a lot of other annotations like @BeforeClass,  @AfterClass, @Ignore, etc.

assertEquals() - This method takes two parameters, the first parameter is the expected output and the second parameter is the actual output. assertEquals will check if the two are the same and will pass or fail the test based on that.

Junit also provides Test suits that help to group tests in different suits. This is very helpful when we have some of the very resource-consuming tests, and we don’t want to run them very frequently. 

FAQs

  1. Which methods Cannot be tested by the JUnit test class?
    A method that is declared as “private,” can only be accessed within the same class. So we cannot test a “private” method of a target class from any test class. 
     
  2. Why is JUnit used?
    JUnit is an open-source framework that is used for writing and running tests.
     
  3. Can we rerun failed test cases in JUnit?
    In the JUnit test framework, a class that allows you to perform retry failed tests is called TestRule. This class will rerun tests that have failed without interrupting your test flow.
     
  4. What is a JUnit test suite?
    The test suite bundles a few unit test cases and runs them together. In JUnit, both @RunWith and @Suite annotations are used to run the suite tests.

Key Takeaways

This article is a basic introduction to the JUnit unit testing framework. We’ve explained how to get started by setting up the environment and writing basic tests. The environment setting part explains the step-by-step process and the required screenshots to make it more interactive. 

Check out JUnit Interview Questions here.

Learning never stops, and to feed your quest to learn and become more skilled, head over to our practice platform Coding Ninjas Studio to practice top problems, attempt mock tests, read interview experiences, and much more.!

Happy Reading!

Previous article
JUnit Plugin with Apache Ant
Next article
Migrating from JUnit4 to JUnit5
Live masterclass