Create tests
The simplest way of creating a new test class in IntelliJ IDEA is by using a dedicated intention action that you can invoke from your source code. In this case, the IDE creates a new test class and generates test code for this class, package, or function.
Add a new test
In your production code in the editor, place the caret at the class for which you want to create a test, press Alt+Enter, and select Create Test.
In the Create Test dialog, select the library that you want to use.
If you don't have the necessary library yet, you will be prompted to download it. To do that, click Fix.
tip
If you're using Maven, the IDE will add the missing dependencies to your pom.xml. For Gradle projects, add the necessary dependencies manually.
Configure the test class name and its location and select the methods that you want to test. Click OK.
As a result, IntelliJ IDEA creates a new test class with the specified name and generated test methods in the Test Sources Root.
Gif
Configure naming pattern for test classes
By default, IntelliJ IDEA adds the Test
suffix to class names when generating test classes. For example, if you create a test class for HelloWorld
, its name by default is HelloWorldTest
. You can change the naming pattern in the settings.
In Settings/Preferences Ctrl+Alt+S, go to Editor | Code Style | Java, and open the Code Generation tab.
In the Naming section of the tab, locate the Test fields and type a suffix or a prefix (or both) that you want to use for generated test classes into the corresponding fields.
Navigate between test code and source code
In IntelliJ IDEA, you can jump between the test classes and the source code.
In the editor, place the caret at the test class or at the test subject in the source code and press Ctrl+Shift+T (Navigate | Test Subject or Navigate | Test ).
If there's only one test for this class, the IDE will navigate you to it right away. Otherwise, you will be prompted to select the necessary test from a popup or create a new test.