How to test a private constructor

H

You can test a private constructor by using Reflection. Insert the following code in your unit test class:

import java.lang.reflect.Constructor;

@Test
public void privateConstructorTest() throws Exception {
    Constructor<MyClass> constructor = MyClass.class.getDeclaredConstructor();
    assertEquals(constructor.isAccessible(), false);
    constructor.setAccessible(true);
    constructor.newInstance((Object[]) null);
}

Add comment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Tag Cloud

Categories