How to exclude source code from coverage measurement in IntelliJ IDEA?

This question is currently over a year old; however, I thought I could offer an alternative to ignoring private constructors in unit tests. Although fairly unlikely, it is possible to circumvent a private constructor in Java. Also, its possible the class could be modified in the future, someone could add a constructor etc... Having a unit test verifying this can feel redundant, but it does add another level of clarity of intent. A failing unit test would certainly catch my eye, "I caused a unit test to fail, am I sure I know what I'm changing here?"

Without further ado here is some sample code.

Here we have a class with a private constructor.

public final class ClassWithPrivateCtor
{
  private ClassWithPrivateCtor()
  {
    throw new AssertionError(String.format(
      "Illegal instantiation of class: %s.",
      this.getClass().getName()));
  }
}

This is one way to invoke a private constructor in Java.

private static <T> void invokePrivateConstructor(final Class<T> type)
  throws Throwable
{
  final Constructor<T> constructor = type.getDeclaredConstructor();

  constructor.setAccessible(true);

  try
  {
    constructor.newInstance();
  }
  catch (InvocationTargetException ex)
  {
    throw ex.getTargetException();
  }
}

And this is how I use it in my unit tests.

@Test(
  description = "Verify ClassWithPrivateCtor private constructor fails.",
  expectedExceptions = AssertionError.class)
public void classWithPrivateCtorTest()
  throws Throwable
{
  invokePrivateConstructor(ClassWithPrivateCtor.class);
}

I've made it a habit to verify private constructors this way just to be clear about the original intent of the class whether its a utility class or a class with constants etc...


I use enum for utility classes and most coverage tools know to ignore it's methods.

public enum Util { ;

enum are final with private constructors by default.