Guides for SE student projects »

This is a WIP community resource, containing contribution from community members.

IntelliJ - Using the JUnit

This tutorial covers the basics of setting up and using JUnit with IntelliJ.

Prerequisites

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.

Setting Up JUnit with Gradle

Add Gradle Support

If your project doesn’t yet use Gradle, follow the Gradle Tutorial to set it up.

Add JUnit as a Dependency

  1. 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.

  2. Follow the instructions here to add the JUnit dependency.

  3. After editing build.gradle, refresh your Gradle project:

    • Press Ctrl ⇧Shift I/ ⌘Cmd ⇧Shift I.
    • In the Gradle tool window, click Reimport All Gradle Projects.

Writing Tests

You can write test classes manually by following this guide. Alternatively, you can let IntelliJ generate test templates for you:

  1. Place your cursor on the class name you want to test.
  2. Press Alt Enter/ Option Enter or right-click and choose Show Context Actions.
  3. Select Create Test from the menu. Create Test option in menu
  4. Choose the methods to generate tests for.

IntelliJ will automatically create a test class and navigate you to it.

Running Tests

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.
Run Tool menu

Writing Useful JUnit Tests

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.

Optional: Create a JUnit Run Configuration

If you want more control over how tests are executed:

  1. Go to RunEdit Configurations from the main menu.
  2. Click + or Ctrl N/ ⌘Cmd N.
  3. Select JUnit from the configuration templates.
  4. Configure options as desired.

Refer to IntelliJ documentation for detailed instructions.

Troubleshooting JUnit

  • Problem: Tests fail with at ClassNotFoundException error, although the supposedly-missing class is present.
    Solution: Ensure the path of source and test files have Unicode characters (e.g., Chinese characters). Gradle sometimes fail to find files in a path that has Unicode characters.

Contributors: Song Yuexi (@YosieSYX)