This is a WIP community resource, containing contribution from community members.
This tutorial covers the basics of setting up and using JUnit with IntelliJ.
As JUnit is a third-party library, you need to add support to it specifically in your project. Given below is how you can do that using the . While it is possible to add JUnit to your project without Gradle, we strongly recommend using Gradle as it can make things easier in the long run.
If you have not done that yet, follow the Gradle Tutorial to add Gradle support to the project first.
This tutorial assumes you are using Gradle to manage JUnit dependencies.
If your project doesn’t yet use Gradle, follow the Gradle Tutorial to set it up.
Open the build.gradle
file in your project’s root directory.
Press Ctrl ⇧Shift O/ ⌘Cmd ⇧Shift O and search for build.gradle
to locate it quickly.
Follow the instructions here to add the JUnit dependency.
After editing build.gradle
, refresh your Gradle project:
You can write test classes manually by following this guide. Alternatively, you can let IntelliJ generate test templates for you:
Show Context Actions
.Create Test
from the menu.
IntelliJ will automatically create a test class and navigate you to it.
You may refer to the JUnit tutorial for how to run your tests.
After running tests, the results will be shown in the Run
tool window.
After you are able to run JUnit tests successfully using a dummy test class such as the above, you can add more tests and test classes as necessary.
To learn how to write useful JUnit test cases, refer to this section of our SE book. For a quick overview of more advanced JUnit features, refer to this section.
If you want more control over how tests are executed:
Run
→ Edit Configurations
from the main menu.JUnit
from the configuration templates.Refer to IntelliJ documentation for detailed instructions.
ClassNotFoundException
error, although the supposedly-missing class is present.Contributors: Song Yuexi (@YosieSYX)