How to write a unit test using JUnit

Introduction

This shot is intended for Java developers with basic knowledge of core Java and Object-Oriented Principles.

This shot provides an introduction to the test-first or test-driven development (TDD) philosophy, which recommends that unit testing and coding go hand-in-hand to ensure your code’s stability.

We will be writing a very simple unit test while developing a simple application.

What is JUnit?

JUnit is a simple, free, open-source framework used to write repeatable unit tests with Java – Erick Gamma and Kert Beck originally wrote it. JUnit is a regression-testing framework that allows developers to write high-quality code faster; its tests increase the stability of the software.

The main philosophy behind this testing framework is to make coding and testing move hand-in-hand.

package io.educative.junit5;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
/* class to be tested */
class HelloWorld {
private String hello;
private String world;
HelloWorld() {
hello = "Hello";
world = "World";
}
public String formMessage() {
String message = hello + " " + world;
return message;
}
}
/* automated unit test */
class HelloWorldTest {
@Test
void checkHelloMsg() {
HelloWorld helloWorldInstance = new HelloWorld();
assertEquals(helloWorldInstance.formMessage(), "Hello World");
}
}

Congrats, the green checkmark indicates that the test was successful!

If the test case fails, a red checkmark and error message will be displayed (execute the code below to see this):

package io.educative.junit5;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
/* class to be tested */
class HelloWorld {
private String hello;
private String world;
HelloWorld() {
hello = "Hello";
world = "World";
}
public String formMessage() {
String message = hello + " " + world;
return message;
}
}
/* automated unit test */
class HelloWorldTest {
@Test
void checkHelloMsg() {
HelloWorld helloWorldInstance = new HelloWorld();
assertEquals(helloWorldInstance.formMessage(), "Hello World!");
}
}

JUnit best practices

Below are some best practices I would recommend while using JUnit in production:

  • Run all the tests in the system at least once per day (or night).
  • If you find yourself debugging using System.out.println(), write a test to automatically check the result instead.
  • When a bug is reported, write a test to expose the bug.
  • Write unit tests before writing the code – only write new code when a test is failing.

Free Resources

Attributions:
  1. undefined by undefined