We can not test private constructors directly by JUnit test. We need to use reflection API to call the constructors.
For e.g we have below class which have a private constructor.
package com.company.main;
import java.lang.reflect.InvocationTargetException;
public class MainClass {
private MainClass(){
System.out.println("From private constructor");
}
}
We have the below test case to use reflection to call the private constructor. If there are any explicit checking is being done by the developer to restrict the calling of private constructor then it may throw exception.
package com.company.test;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import org.junit.jupiter.api.Test;
import com.company.main.MainClass;
class MainTest {
@Test
void test() throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Constructor<MainClass> constructor = MainClass.class.getDeclaredConstructor(new Class[0]);
constructor.setAccessible(true);
MainClass mainClass = constructor.newInstance(new Object[0]);
}
}
For e.g we have below class which have a private constructor.
package com.company.main;
import java.lang.reflect.InvocationTargetException;
public class MainClass {
private MainClass(){
System.out.println("From private constructor");
}
}
We have the below test case to use reflection to call the private constructor. If there are any explicit checking is being done by the developer to restrict the calling of private constructor then it may throw exception.
package com.company.test;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import org.junit.jupiter.api.Test;
import com.company.main.MainClass;
class MainTest {
@Test
void test() throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Constructor<MainClass> constructor = MainClass.class.getDeclaredConstructor(new Class[0]);
constructor.setAccessible(true);
MainClass mainClass = constructor.newInstance(new Object[0]);
}
}