Unit Testing in Java

Laide Endeley
2 min readMay 21, 2021

Unit testing simply means testing smaller units of your application, like classes and methods.

It is usually good practice to test your code so that you can prove to yourself, and possibly anyone who gets to see our use you code that it works.

Unit tests are normally automated, this means that once they are implemented, you can run them again and again.

This article uses JUnit to implement the unit tests.

A Simple Unit Test Example

In this article, you will learn how to implement a simple unit test JUnit.

First I will show you the class I want to test:

public class MyUnitTest {
MyUnit myUnit = new MyUnit();

@Test
public void testAdd() {
int result = myUnit.add(1, 2);
assertEquals(3, result);

}
}

I just made a simple class so that you can easily understand what is going on.

So, to test this class I need a unit test that will test each public method in my class. This class has only one public method, add(), so all I need to test is this single method.

Here is the JUnit unit test that tests the add() method:

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class MyUnitTest {
MyUnit myUnit = new MyUnit();

@Test
public void testAdd() {
int result = myUnit.add(1, 2);
assertEquals(3, result);

}
}

The unit test class is an ordinary class, with one method, testAdd(). Notice how this method is annotated with the JUnit annotation @Test. This is done to let the unit test runner know, that this method represents a unit test, and it should be executed. Methods that are not annotated with @Test are not executed by the test runner.

Inside the testAdd() method, an instance of MyUnit is created. Then the add() method is called with two integer(int) values.

Finally, the assertEquals() method is called. It is this method that does the actual testing. In this method we compare the output of the called method (add()) with the expected output. In other words, we compare “3” (expected output) with the value returned by the add() method, which is kept in the variable result.

If the two values are equal, nothing happens. The assertEquals() method returns normally. If the two values are not equal, an exception is thrown, and the test method stops executing here.

You can have as many test methods in a unit test class as you want. The test runners will find them all, and execute each of them. I just used one test method in this example, so it can be very easy to understand.

This is how simple a unit test can be done with JUnit.

--

--