When I was looking at the test code written in JUnit today, the test for the private method was not written. I made a sample that calls a private method, so I thought I'd post it.
Postscript For details, please refer to @ Kilisame's comment, but it is not an article that says that I tested it because I forgot to test private. It's hard to say that the caller's public test can't be done .... (I'd like you to understand), so I wrote it because I wanted to at least do a private test.
import static org.junit.Assert.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.junit.Test;
/**Sample class*/
public class private_Test {
	public class Sample{
		private int fuge(int i) {
			return i;
		}
	}
	
	@Test
	public void test() {
		
		Sample sample = new Sample();
		try {
			Method method = Sample.class.getDeclaredMethod("fuge", int.class);
			method.setAccessible(true);
			int rtn = (int)method.invoke(sample, 2);
			assertEquals(2,rtn);
			
		} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
			//TODO auto-generated catch block
			e.printStackTrace();
		}
	}
}
You can get the method with the getDeclaredMethod () method, allow external access with setAccessible (true), and execute it with method.invoke ().
Recommended Posts