Member-only story

Java Programming Language: JUnit Unit Test Tutorial

Jesse L
3 min readFeb 13, 2022

--

Hi everyone, welcome back. Today, we will cover how to write a unit test using JUnit in Java. Unit testing is used to check and validate that a portion of code is working or behaving the way it is supposed to. Unit tests are extremely helpful when it comes to bug fixing and error handling. Let’s go over the basics of unit testing.

Creating a Function to Unit Test

Let’s create a simple function so we can see how to unit test. I’m going to create a mathematical function in a class. This function is going be named “onePlusTwo()” and is going to return 3. See my class and function below:

public class MyUnitTestExample {
public static int onePlusTwo() {
return 3;
}
}

So now that we have a simple function within a class, let’s see how we can unit test this.

Writing a Unit Test for our Function

Now we are going to create a new file for JUnit. I am using New JUnit Jupiter Test, so keep in mind that things may be different if you are using JUnit 4 or JUnit 3. We are now going to write a test to test if our function works correctly:

import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;

--

--

Jesse L
Jesse L

Written by Jesse L

Hi, I'm a passionate technology enthusiast and lifelong learner. Beyond my technical pursuits, I'm also passionate about sharing my enthusiasm with others.

No responses yet