Test private methods

Sometimes a method you want to test is private and cannot be called directly from a junit test. Of course you could change visibility to public, but I don’t think it is a good idea.

Spring ships with some nice support for this case:

import static org.junit.Assert.assertEquals;

import org.junit.Test;
import org.springframework.test.util.ReflectionTestUtils;

public class SomeTest {

    @Test
    public void testSomething() {
        SomeClass someClass = new SomeClass();
        SomeResult result = ReflectionTestUtils.invokeMethod(someClass, "someMethod", someArgument1, someArgument2);
        assertEquals("xxx", result);
    }
}