Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JaCoCo and missed coverage of private default constructor

I'd like to see an example to prevent JaCoCo to report private empty constructors as non-covered code in a Java class.

In the maven plugin configuration I have

   <rule>
     <element>CLASS</element>
       <excludes>
         <exclude>JAVAC.SYNTHCLASS</exclude>
         <exclude>JAVAC.SYNTHMETH</exclude>
       </excludes>
     </element>
   </rule>

Isn't there something similar for the constructor?

like image 807
mat_boy Avatar asked Mar 11 '16 21:03

mat_boy


1 Answers

For this use case, reflection is perfectly acceptable, there are few and well known classes. The bellow code could be used with an automatic class detection based on the name. For sample ".*Factory" classes with additional asserts.

@Test
public void testCoverage()
    throws SecurityException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
    coverageSingleton(MySingleton1.class);
    coverageSingleton(MySingleton2.class);
}

private <S> void coverageSingleton(Class<S> singletonClass)
    throws SecurityException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
    final Constructor<S> constructor = singletonClass.getDeclaredConstructor();
    constructor.setAccessible(true);
    constructor.newInstance();
}
like image 178
fdaugan Avatar answered Oct 31 '22 03:10

fdaugan