In this post, I will go over how to create a unit test in Java using JUnit. Creating a unit test in Java is very straightforward. We need to do the following steps:
- Include the JUnit dependency
- Have a class you want to test
- Create a test class
The first step is to include the following dependency in your pom.xml file. This only works if your project uses Maven.
This dependency adds the JUnit library to your project. By including the dependency from the example in your pom.xml file you can use JUnit to create unit tests.
The class to test
To show you how to create a unit test we need a test to class. I created the following class at the following location:
/src/main/java/com/davidvlijmincx/Car.java. This is important because the test class will mostly use the same directory structure.
The previous class
car only has a single method called
makeSound that we will test in the next step. We are going to verify if the method returns
the expected result.
The test class
The next step is to create the test class. If you are using IntelliJ you can use ctrl + shift + t to create the test file in the right directory.
To test the
Car class you need to create a CarTest that will hold the test methods. To test the Car class I created the following class:
A lot happens in this class so let's go over it one by one:
importstatements are there to tell Java which libraries are used inside the class
class CarTestis the class that will hold the testing methods
- A method annotated with
@Testmakes it clear to Maven and your IDE which methods are tests
assertEqualschecks if the result matches with the sound we expected from the
When you create a test in Java it is important to place it inside the test directory. The test directory uses the same directory structure
as the src folder. For the project holding the
Car class it looks like the following:
As you can see Car and CarTest classes are located inside the same directory structure. The difference is that the production code
is placed inside the
src directory and the test code is placed in the
Running the test with Maven
If your Maven version does not support JUnit5 test you need to include the following configuration in your pom.xml.
After including the previous configuration you can use the following command to run the test using Maven:
Maven should now be able to run the tests you just created.
In this post, we looked at how to create unit tests using Java and JUnit5.