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.
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 {@Testvoid 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 {@Testvoid checkHelloMsg() {HelloWorld helloWorldInstance = new HelloWorld();assertEquals(helloWorldInstance.formMessage(), "Hello World!");}}
Below are some best practices I would recommend while using JUnit in production:
Free Resources