This tutorial will show how to use IntelliJ IDEA for developing unit tests and analyzing coverage.
This page should redirect to https://www.jetbrains.com/idea/help/testing.html.
Create a Java project from scratch with the name UnitTestingApp.
Now let's create a class, which we are going to test.
Add method sayHello which returns a "Hello" string.
Instead of adding tests to the sources, you can mark any directory as a test source root, so tests will be separated from the production code.
Create a directory and mark it as a test source root.
IntelliJ IDEA provides a shortcut Cmd + Shift + T for navigating between classes and its tests. It also lets you to create a test class from right there.
Select JUnit 4 as the library for unit testing. IntelliJ IDEA will offer to add this library to the module. Choose to generate setUp method, and test for sayHello method.
If the project has several source roots, the IDE will ask you to choose one to put new test class in.
When the test class is generated, we can add code for our test method testSayHello.
Now we can run our test via the context menu Run 'MyClassTest' on the class, or via Run → Edit Configurations.
Results will appear in theRun tool window.
We can adjust the run configuration of our tests via Run → Edit Configurations or via the toolbar.
On theConfiguration tab you can choose which tests must be run. For instance, you can run all tests from a class, package, test suite or even by pattern. Fork mode is here to let you run each test in a separate process.
On theCode Coverage tab you can adjust coverage settings. Currently IntelliJ IDEA supports two engines for measurement coverage. By default it uses own engine. Optionally, you can choose theJaCoCo engine. Also you can select coverage mode here. Tracing mode adds overhead but is more accurate in measurement.
To collect coverage, you need to run tests in special mode via Run → Run 'MyClassTest' with Coverage or action on the toolbar.
After at least one test run in coverage mode, the IDE shows coverage data in theProject tool window for each package and class, as well as in theCoverage tool window, and right in the editor.
If you add another method to MyClass and run tests with coverage, you will find that the code not covered by any tests is highlighted with red. The covered code is colored with green. If some code is covered only partly, it will be highlighted with yellow.
You can download the source code for this tutorial from GitHub.