Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

This tutorial will show , how to use IntelliJ IDEA for developing unit tests and analyzing coverage.

1. Create new project from scratch

Create a Java project from scratch with the name

span
classid
UnitTestingApp
.
E

2. Create a class to test

...

Add method

span
classid
sayHello
returning hello which returns a "Hello" string.

3. Create a test source root

Instead of adding tests to the sources, you can mark any directory as a test source root. In this case , so tests will be separated from the production code.

...

IntelliJ IDEA provides a shortcut

span
classshortcut
Cmd + Shift + T
for navigating between classes and its tests. It also lets you to create a test class from right from there.

Select JUnit 4 as a the library for unit testing. IntelliJ IDEA will offer to add this library to the module. Choose methods to generate setUp method, and test for sayHello methodsmethod.

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

span
classid
testSayHello
.

...

Now we can run our test via the context menu

span
classshortcut
Run 'MyClassTest'
on the class, or via
span
classshortcut
Run → Edit Configurations
.

Results will appear in the

span
classid
Run
tool window.

...

6. Edit tests configuration

We can adjust the run configuration of our tests via

span
classshortcut
Run → Edit Configurations
or action on via the toolbar.

On the

span
classid
Configuration
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.
span
classid
Fork mode
is here to let you run each test in a separate process.

On the

span
classid
Code 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 the
span
classid
JaCoCo
engine. Also you can select coverage mode here.
span
classid
Tracing{span{
mode add adds overhead but is more accurate in measurement.

Image Modified

7. Run with coverage

To collect coverage, you need to run tests in special mode via

span
classshortcut
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 the

span
classid
Project
tool window for each package and class, as well as in the
span
classid
Coverage
tool window, and right in the editor.

...

If you add another method to

span
classid
MyClass
and run tests with coverage, you will find , that the code uncovered 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.

...