Java code coverage in Eclipse

Besides testing, Java code coverage can be a very effective debugging tool as it helps you see which code is ran.

EclEmma is a great Java code coverage tool that has an Eclipse plugin.

It's very simple and intuitive and has all you would expect from a code coverage tool. With it, you can:

  • See code coverage for a java application that you've run (and potentially merge multiple run instances)
  • See code coverage for jUnit tests and maven tests
  • See which classes have which amount of coverage.
  • And more!

To use it, you can either right-click on a class and then find and click Code Coverage > Run As, or you can just hit the Run As Code Coverage button that looks like the regular Run button (shown here):

In the screen shot below, the colors are fairly self-explanatory. The color yellow means that it ran into a conditional (if/select/try) and only executed one branch.

To install EclEmma, just search for 'eclemma' in the market place:

If you decide to try this plugin out, I recommend you read the EclEmma user guide to get acquainted with all of its features (it's fairly short, only 15 mins of reading).

Sometimes you just need to cover a small part of your code (e.g code ran when issue occurs), to narrow down an issue. You can reset code-coverage during a session for such situations.

(Make sure to check 'Reset on Dump').

Sometimes code is not interactive and you need to reset the the code coverage session programatically. Then you can use their api:

// code that you're not interested in

Object jacocoAgent;
try {
jacocoAgent = YOUR_CLASS_NAME.class.getClassLoader().loadClass("org.jacoco.agent.rt.RT").getMethod("getAgent").invoke(null);
jacocoAgent.getClass().getMethod("reset").invoke(jacocoAgent);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException | ClassNotFoundException e) {
e.printStackTrace();
}

// Code you want to cover

System.exit(0); // End the session early

// Code that you're not interested in

(src)

Further reading:

Main Web-page: http://www.eclemma.org/
Api: http://www.jacoco.org/jacoco/trunk/doc/api/index.html

 

Last updated: February 11, 2024