Writing Unit Tests in Java Creating a JUnit5 Test Class

Learning objective: By the end of this lesson, you’ll be able to create and setup a JUnit5 test class in IntelliJ IDEA IDE for any class that’s part of your source code.

Creating a JUnit5 test class in IntelliJ IDEA IDE

In this module we’ll learn how to create a JUnit5 test class that can be used to code automated tests that run on our Calculator class.

Step 1

Open the src/test directory in the Project tool window. Note the child java directory icon is green and the directory has a green background.

In the Project tool window, the src/test/java directory is colored with a green background.

🧠 You may have noticed before that the src/main/java directory’s icon is blue, which indicates it is the Sources Root.

Step 2

Open the src/main/java/org/example/Calculator.java file. Click the Calculator class name so that the caret is somewhere inside the text and the Calculator text is highlighted in orange as shown outlined in the screenshot below.

The caret placed in the Calculator class so it is highlighted in orange.

With the caret here, use ⌥ Option + ↩ Enter (Alt + Enter in Windows and Linux) then select the Create test option shown outlined in red in the screenshot below.

Creating a test for the Calculator class. The Create test option is outlined in red.

Step 3

A Create Test dialog box will appear. Create the new test with the below options:

We need to add the JUnit5 library to our project to use it. Once your Create Test dialog box looks like the one in the screenshot below, select the Fix button.

It might not look like anything is happening after you click this button, but in the background, the appropriate libraries should now be in your project.

After you’ve clicked the Fix button, click the blue OK button.

In the Create Test dialog box, the correct values have been entered/selected and the Fix button is outlined in red.

This will create a new CalculatorTest class in the src/test/java/org/example/CalculatorTest.java file, ready for you to start writing tests in.

The new CalculatorTest class.