Writing tests is an important part of a developer’s job, however, it can be boring. Especially if you are not a TDD fan and leave the tests for after the code is done, so that you have to write a big batch of unit tests at once. How to break the monotony and add at least some element of challenge to this routine? Enter running tests with coverage.
In IntelliJ Idea, which I have been happily using for quite some time, it’s quite simple to run tests with coverage and there’s a whole manual entry on how to do that. So when you act on the manual, you will see the results of the coverage report and they will look somewhat like that:
The icon with the green arrow on the left will generate a coverage report, that will open in a browser. When you navigate to the class you’ve been testing from there, you will see something like that:
So, there’s a method getTemplatePages() which has been partially covered by the unit tests, but we see that only the “happy path” is covered. That’s not good. Let’s write one more test case for this.
Afterwards, when we run the unit with coverage again, it looks much better!
When you run tests with coverage report, you have to color as many lines as you can with the green color. After a while, it becomes a kind of a game, to see how many cases you can invent to cover as much as you can, and also you have to think about what kind of tests really make sense and what kind of tests are just a waste of space and time, no matter the coverage. So you start testing mindfully and sensibly, and in the end it is what this is all about, not just reaching a perfect percentage.
Good luck with the testing game!