Java Private constructor in Junits

115 Views Asked by At

I've a class with few constants declared, initialized and I also have a private constructor. For some reasons I'm writing Junits to achieve the code coverage. Here I have used constructor.setaccessible(true) and I have initialized the class.

In the assert statement I'm expecting the length of the constructor to be 1.

I've achieved 100% code coverage for this class. But I'm quite not sure how. Can anyone please throw some light on this?

public class CommonConstants {
  public static final String ABC= "ABC";
  public static final String XYZ= "XYZ";

  private CommonConstants() {}
}

@Test
public void stringTest() {
     final Constructor<?>[] constructors = CommonConstants.class.getDeclaredConstructors();
     constructors[0].setAccessible(true);
     try {
          CommonConstants cc = (CommonConstants) constructors[0].newInstance();
     } catch (InstantiationException e) {
          e.printStackTrace();
     } catch (IllegalAccessException e) {
          e.printStackTrace();
     } catch (InvocationTargetException e) {
          e.printStackTrace();
     }
     Assert.assertEquals(1, constructors.length);
  }
0

There are 0 best solutions below