JUnit Tutorial For Beginners – What Is JUnit Testing

This JUnit Tutorial for Beginners explains what is Unit Testing, Test Coverage and What is JUnit Testing Framework along with Examples of JUnit Testcases:

This JUnit series has been prepared to focus on our audiences who are absolute beginners as well as those who have a good knowledge of Java or JUnit with a keen interest in learning JUnit.

The series in totality has been put forth in such a way in which you will able to interpret the difference between JUnit 4 and Junit 5.

Let’s start exploring JUnit now!!

JUnit tutorial

List Of Tutorials In This JUnit Series

Tutorial #1: JUnit Tutorial For Beginners – What Is JUnit Testing?[This Tutorial]
Tutorial #2: Download, Install And Configure JUnit In Eclipse
Tutorial #3: JUnit Tests: How To Write JUnit Test Cases With Examples
Tutorial #4: What Is A JUnit Test Fixture: Tutorial With JUnit 4 Examples
Tutorial #5: Multiple Ways To Execute JUnit Tests
Tutorial #6: List Of JUnit Annotations: JUnit 4 Vs JUnit 5
Tutorial #7: JUnit Ignore Test Case: JUnit 4 @Ignore Vs JUnit 5 @Disabled
Tutorial #8: JUnit Test Suite & Filtering Test Cases: JUnit 4 Vs JUnit 5
Tutorial #9: JUnit Test Execution Order: Order Of Tests JUnit 4 Vs JUnit 5
Tutorial #10: How To Use JUnit 5 Annotation @RepeatedTest With Examples
Tutorial #11: JUnit 5 Nested Class: @Nested Tutorial With Examples
Tutorial #12: JUnit 5 Custom Display Name & Conditional Test Execution
Tutorial #13: JUnit Vs TestNG – What Are The Differences
Tutorial #14: JUnit API Additional Classes: TestSuite, TestCase And TestResult
Tutorial #15: JUnit Assertions: AssertEquals And AsssertSame With Examples
Tutorial #16: Grouped Assertions In JUnit 5 – Tutorial With Examples

JUnit Tutorial

In a typical, test-driven development (TDD) approach, developers focus on unit testing every chunk of the code they develop. The better the testing of a product, the better is the quality of it. We all know, that testing should go parallelly with each passing phase of the software development life cycle.

Starting from requirement and analysis to design & development till maintenance, every phase should have an appropriate testing phase associated with it. Unit testing after development is what is advisable to build a robust application and to have an optimized code in place.

What Is Unit Testing?

Unit testing is testing of a small logic or a code to verify that the output of the code is as expected on the input of a specific data and/or on satisfying certain condition(s). Usually, the unit tests are supposed to be independent of the other tests.

Unit tests are not feasible to test complex interfaces with another application or third party/external services. A unit test targets only a small unit of code that could be just a method or a class.

It helps the developer discover issues in the current logic and any regression failures due to the current change. Besides, it also provides insight into how the current code could impact future implementation.

Unit Testing

Test Coverage

The percentage of code that is tested by unit tests is called test coverage.

The objective is to have better and more test coverage of the code which in future continues to add up to the regression test suite and helps to increase automated test execution and verification, thereby, reducing the manual effort involved in regression testing.

Running tests automatically helps to identify software regression issues introduced by changes in the current code. Having a high-test coverage of your code allows you to continue developing features without having to perform a lot of manual tests.

Many come with a question as to how much test coverage is essential. The answer to this question is that there is no hard and fast rule to how much coverage of tests is essential; it is all judgemental. The judgment gets better with experience on the application workflow and historic knowledge of the defects found so far.

Efficient tests need not necessarily mean having 100% test coverage or incorporating automation tests and/or unit tests for every single branch or path coverage.

Certain trivial verifications like a validation error message for a mandatory field left blank that hasn’t flawed since years need not be included in the regression suite.

Manual Testing Vs Automated Testing

Unit Testing can be done via two approaches:

  1. Manual testing
  2. Automated testing

JUnit Testing Approaches

In both the approaches the workflow remains common:

  1. Creating a test case
  2. Reviewing it
  3. Rework if corrections needed
  4. Execute the test case
  5. Analyze the test results

Automated Testing is preferred over Manual Testing for the below reasons:

Manual TestingAutomated testing
When a testcase is executed manually without an intervention of a tool is called manual testing.When a testcase is executed with the help of a tool without much manual intervention is called automated testing.
Repetitive manual efforts are included.Repetitive manual efforts may be avoided.
Human efforts in manual testing could be erroneous and time consuming. Automation tests are faster and error free compared to the manual efforts.
Testing resources required are more for running every testcase manually thereby, adding to the investment in the resources.Less testers are needed to execute automated tests using the designated automated tool(s) hence there is less investment in testing resources thus adding to the profitability.
Manual testing has to be limited to a small test coverage considering the timeline restrictions. Hence, there is a risk of skipping many test scenarios thus leading to risk of defect leakage as well.Many different test scenarios can be automated and can be executed multiple times even under time and resource crisis hence leading to better test coverage and better quality of the deliverable.

Unit Test Framework

We may have the next question as to what does a typical automation unit test case looks like and the framework it follows. The developers use the Unit Test framework for creating automated unit test cases.

  1. In order to verify if the code is logically working as expected, a testcase with a specific checkpoint or verification criterion is created.
  2. When the testcase is executed, either the criteria/condition passes or fails.
  3. A log is generated as per the testcase workflow.
  4. The framework will report a summarized result on the passed test cases and failed ones.
  5. Per the severity of the failure, the testcase may not proceed further and may stop subsequent execution.
  6. There could be certain low severe failures that get reported in the log however it doesn’t show a hard stop but continues without blocking the further test steps.

What Is JUnit?

JUnit is an open-source framework that is used for writing and executing unit tests in Java programming language. It is one of the best-known unit testing frameworks.

The below image shows the different well-known automation unit testing tools.


Enlisted below are the attributes that JUnit is packaged with:

  • There is a humongous list of Annotations to identify, execute, and support many features for the test methods.
  • There are Assertions for verifying the expected results.
  • It provides Test Runner for executing the tests.
  • JUnit provides a basic built-in template so that you may write small, simple test cases in no time.
  • JUnit tests help you to write independent modules, thereby bettering the coverage of the test and the quality of the application.
  • It not only allows easy creation and execution of tests but also presents the developer with a clean and clear explicit report that eliminates the need for the developer to search through the path of the reports and test results.
  • Until the test execution is sailing through smoothly, you may relax watching at the green-colored test progress bar that shows while execution is in progress whereas it alerts you in ‘red’ as soon as the test fails a verification checkpoint.
  • Test suites can be created in order to put a sequence or related set of test cases together.

Examples Of JUnit Testcase

Given below are the two examples of a very basic Hello World program to get an understanding of how a JUnit test class looks like or how different does it look when compared with a usual Java class file.

Example #1:

Here is a JUnit testcase HelloWorldJUnit.java that verifies that the string “Hello world” matches the string “hello world” which fails on execution, as the match is case sensitive. Hence, the two strings don’t match and the test fails.

The code for HelloWorldJUnit.java

package demo.tests;
import static org.junit.Assert.*;
import org.junit.Test;
public class HelloWorldJUnit {
	public void test() {
		assertEquals("Hello world","hello world");	

Example #2:

Here, we will see how a usual Java class file interacts with a JUnit testcase. We create a Java class file HelloWorld_Java.java with a constructor that allows us to pass a String value and a method getText() to fetch the string value.

JUnit Test class HelloWorldJUnit.java is created such that the class object for HelloWorld_Java is created and the actual string value is passed to the object. The assertEquals() from JUnit verifies if the expected and actual string values match.

The code for HelloWorld_Java.java

package demo.tests;
import static org.junit.Assert.*;
import org.junit.Test;
public class HelloWorldJUnit {
	public void test() {
		assertEquals("Hello world","hello world");	

The code for HelloWorldJUnit.java

package demo.tests;
public class HelloWorldJUnit{
	private String s;
	public HelloWorld_Java(String s) 
		public void test() {
		HelloWorld_Java hw=new HelloWorld_Java("Hello World");
		assertEquals(hw.getText(),"Hello World");	

The resultant looks like below where we see the two strings match. Hence, JUnit test is passed.



When it comes to providing you a quick overview of what JUnit is and what it does, JUnit is a beautifully crafted framework that enables you to create and execute unit tests in an automated way.

It is an open-source tool yet so hassle-free. Be it the creation of test cases or execution of a testcase or reporting after execution or maintaining the tests, JUnit is elegant in every aspect. Yes, it can fail elegantly too; and we will see how that happens in our upcoming tutorial as we move on.

About the Author: This tutorial has been written by Shobha D. She works as a Project Lead and comes with 9+ years of experience in manual, automation and API Testing.

Let us continue to illuminate deeper on every aspect of JUNIT here-on.

NEXT Tutorial