How to test a private constructor in Java application? [duplicate]

Using reflection, you can invoke a private constructor:

Constructor<Util> c = Utils.class.getDeclaredConstructor();
c.setAccessible(true);
Utils u = c.newInstance(); // Hello sailor

However, you can make even that not possible:

private Utils() {
    throw new UnsupportedOperationException();
}

By throwing an exception in the constructor, you prevent all attempts.


I would make the class itself final too, just "because":

public final class Utils {
    private Utils() {
        throw new UnsupportedOperationException();
    }
}

Test the intent of the code .. always :)

For example: If the point of the constructor being private is to not be seen then what you need to test is this fact and nothing else.

Use the reflection API to query for the constructors and validate that they have the private attribute set.

I would do something like this:

@Test()
public void testPrivateConstructors() {
    final Constructor<?>[] constructors = Utils.class.getDeclaredConstructors();
    for (Constructor<?> constructor : constructors) {
        assertTrue(Modifier.isPrivate(constructor.getModifiers()));
    }
}

If you want to have a proper test for the object construction, you should test the public API which allows you to get the constructed object. That's the reason the said API should exist: to build the objects properly so you should test it for that :).