How to create a new JUnit5 test (Canary Test) for a Java project in IDEA

created at 03-20-2022 views: 7

tool

  • IDEA2021.3 *javaJDK17
  • JUnit5

purpose

Mainly learn Test Driven Development (TDD) and Continuous Integration (CI). So create test classes first, instead of writing source code. Get used to this gradually.

Step 1: Create a new java project

create project

Step 2: Create and set up the test folder test

Click the project name tictactoeapp, right-click to create a new package, name it test, and use it as a test.

Click the small gear in the upper right corner and enter project structure.

configuration

Then go to modules, select sources, mark the test folder as a test

modules

The result marked as a test is shown below, click apply and exit.

mark as test

Then we weill find that the test folder in the directory structure turned green.

test folder turned into green

Step 3: Create the corresponding package and test class

Corresponding project structure

structure

Note: The packages in the src and test folders must be the same. Here the test class TicTacToeTest is created in test/game/

Step 4: Write Canary Test and include the corresponding dependencies

  • Canary Test: This test is mainly used when creating a new test project to test whether the machine environment you are working on is configured correctly.
  • Canary Test is arguably the simplest test, testing things like true is true directly.

If an error is reported using the annotation @Test, there are two ways to deal with it.

  • The first method, as shown in the figure below, is added to the classpath, which is to be downloaded. Specifically as shown in the figure below

download

download

  • The second method is to use the local jar package (downloaded by myself, and the first method is also downloaded to the local), here I use the second one. The specific operation process is as follows:

As above, click the gear in the upper right corner, go to project structure -> modules -> dependencies, select the plus sign, and add the local test jar package

configure

The location of the local jar package

location of the local jar package

After the import is complete, the local jar package will appear

local jar package will appear

Then we found that the @Test annotation did not report an error, but the new problem occurred that assertTrue could not be resolved, just alt + enter import static xxx

test code

package game;

import org.junit.jupiter.api.Test;

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

public class TicTacToeTest {
    @Test
    public void Canary() {
        assertTrue(true);
    }
}

Step 5: Do the Canary Test

test success

The test shown above in green is successful.

created at:03-20-2022
edited at: 03-20-2022: