1

Write a java program to get the statement coverage of JUnit test cases?

for example:

public Integer addIfXGreaterThanY(int x, int y){
   Integer z = null;

   if (x > y) {
       z  = x + y;
   }
   else {
      z = x - y;
   }

   return z;
}

Output:

Test case 1 inputs:  10, 15
output(line numbers covered):  1, 2, 5, 6
and another call will produce:
Test Case 2 inputs: 15, 10
output(line numbers covered): 1, 2, 3, 6
Stefan Birkner
  • 24,059
  • 12
  • 57
  • 72
Moni
  • 39
  • 6

2 Answers2

3

Sounds like you are looking for code coverage reporting tools. These libraries provide the lines and branches of code covered and missed by test cases (usually include junit). Tools like Jacoco and cobertura usually provide the lines and branches covered in your methods by tests. Some more examples of java code coverage tools are available. Personally, I've used jacoco with junit before.

Perhaps you want a comparison of some of the existing code coverage tools?

  • Thanks a lot for your detailed information. I am actually trying to build one such tool. Are there any pre-defined classes in java like 'Instrumentation' which can help me find statement coverage of junit test cases. – Moni Oct 26 '17 at 18:54
  • Haven't personally worked on building reporting tools but maybe starting with how the tools actually work and what theory they are based on will help? Related question for jacoco : https://stackoverflow.com/questions/3051563/how-do-code-coverage-tools-work . Maybe you want to add another question or reframe your question if your question doesn't exist? – Aurgho Bhattacharjee Oct 26 '17 at 19:11
2

What I think you want is called code coverage. Emma is one popular tool for JUnit code coverage. The answers at this question have some other options also.

Freiheit
  • 8,408
  • 6
  • 59
  • 101
  • Thank you for your answer. Is it possible to write a java program to find the statement coverage instead of using automated tools? Can we use Instrumentation class instead? – Moni Oct 26 '17 at 18:40
  • @Moni you should edit your question to clarify that you want to *Write* a code coverage tool instead of just using one – Freiheit Oct 26 '17 at 19:10
  • I have now edited my question as required. Thank you – Moni Oct 26 '17 at 19:36