How to get Code Coverage using EclEmma

In Test-Driven-Developement writing JUnit tests is a must. But often developers tend to write them just a by-product. Not taking JUnit tests serious can have dramatic effects in the long run. Imagine you think your refactoring was successfully because you Unit-Tests are still all green, but in reality you just did not cover the refactored code in your tests. There are several tools that help you to check how good you code coverage is. The most popular one for Eclipse is EclEmma.

Installing EclEmma

First of all you need to install EclEmma. To do that open Eclipse and go to

Help –> Eclipse Marketplace and search for EclEmma.

Follow the intallation instructions and restart Eclipse.

Writing a bit of Code

To successfully test the code coverage tool we need a small code base to work on. So create a new Java Project with the following structure.

Writing a JUnit-Test

Let´s write a JUnit-Test to verify whether our makeSomeNoise() method works the way it should. When you write Tests the method name should speak for itself, so try to follow this convention. public void methodName_WhatIsTheInputWhatIsTheResult

Get 100% Code Coverage

So we run our Unit test successfully, let us check our code coverage.
To do that

Right Click on Cat Test –> Coverage as –> JUnit Test

This is what we get:

We can see that our class has a code coverage of 75%. This is not enough you should always aim to get something like 90%+.
EclEmma is kind enough to tell us what code is not covered yet. The if-case. Hover over the yellow part of the code and you will se a tooltip “1 of 2 branches missing”. This means that only one case is tested. We have not tested what our method is doing when the cat is lazy. Therefore the uncovered code is red.

Get to 100%

To get a coverage of 100% we need to write another test which covers the case that our cat is indeed lazy.