[Java] How to set when The constructor Empty () is not visible occurs in junit
Summary of this article
I had a little trouble when using junit with eclipse, so I will describe the setting method as a memorandum.
Specifically, the following error may occur when the test target class has a private constructor, so the workaround is described.
The constructor Empty() is not visible
reference
How to test private methods in Junit
[Get method, execute method with Java reflection API]
(http://pppurple.hatenablog.com/entry/2016/07/23/205446)
environment
OS:Windows8.1 32bit
eclipse:4.5.2
Tested class
TestTarget.java
packege com.web.test
public class TestTarget {
private TestTarget() {
//No description
}
private int minus(int x, int y) {
return (x - y);
}
}
junit test class
Create a junit test class for the class under test
SampleTest.java
import static org.junit.Assert.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.junit.Test;
public class SampleTest {
@Test
public void test()
throws NoSuchMethodException,
SecurityException,
IllegalAccessException,
IllegalArgumentException,
InvocationTargetException
{
TestTarget testTarget = new TestTarget();
Method method = Sample.class.getDeclaredMethod("minus", int.class, int.class);
method.setAccessible(true);
int actual = (int)method.invoke(testTarget, 8, 2);
assertEquals(6, actual);
}
If you do this
The constructor Empty() is not visible
Has occurred, so change it as follows
SampleTest.java
import static org.junit.Assert.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.junit.Test;
public class SampleTest {
@Test
public void test()
throws NoSuchMethodException,
SecurityException,
IllegalAccessException,
IllegalArgumentException,
InvocationTargetException
{
//Before correction
//TestTarget testTarget = new TestTarget();
//Revised
//Get an instance of the class under test using the reflection API
TestTarget testTarget = Class.forName("com.web.test.TestTarget").newInstance();
Method method = testTarget.class.getDeclaredMethod("minus", int.class, int.class);
method.setAccessible(true);
int actual = (int)method.invoke(testTarget, 8, 2);
assertEquals(6, actual);
}
with this
The constructor Empty() is not visible
Has been resolved