How to add Jacoco Test Coverage static member variables?

I have a class as follows:

public class XConstants { public static final int A_TYPE = 1; public static final int B_TYPE = 2; } 

I use both variables in my tests, but when I examine the test coverage with Jacoco, it shows% 0 to cover this class. I assume this is because I never instantiated this class, just use its static variables. I tried to create an instance, and the test coverage is% 100. How can I solve this problem?

+7
source share
4 answers

JaCoCo measures test coverage based on the percentage of bytecode that was actually executed. Declaring a static final primitive or String constant does not generate bytecode to execute, it is just a record inside the constant pool. The only bytecode you have is an implicit default constructor, usually like this:

 aload_0 invokespecial Object.<init> return 

Therefore, when you do not name it, you have 0%, if you name it, you have 100%.

My suggestion is to ignore this problem. You should not try to achieve 100% coverage, no matter what. In the end, this does not guarantee anything: even 100% code can contain serious errors.

+5
source

You created a class that can be created, but you never created it, so technically you did not use this code. A simple solution for a โ€œclass full of constantsโ€ is to make it an interface. Also note that the variables in the interface are public, static, and final by default, so your code might look something like this:

 public interface XConstants { int A_TYPE = 1; int B_TYPE = 2; } 
+2
source

In our project, we overcome the problem of lack of coverage for a class containing only constants by creating a private constructor (the following template from java.lang.Math ):

 private XConstants {} 

and then using Trajano commons-testing to claim that this constructor is private and calls it to cover:

 assertUtilityClassWellDefined(XConstants.class) 
+1
source

[Updated] jacoco 0.8.0 is configured by default, so you need to add a private constructor for it to work.

0
source

Source: https://habr.com/ru/post/986814/


All Articles