[Spring](EN) Test private variable or method(function) using ReflectionTestUtils

Test private variable or method(function) using ReflectionTestUtils


Environment and Prerequisite

  • Java
  • Spring


ReflectionTestUtils

Target Class

@Component
@Getter
public class ReflectionTestUtilsComponent {

    private int privateValue;

    private int privateMethod(int a, int b) {
        privateValue += a;
        privateValue += b;
        return privateValue;
    }
}


private Variable Test

Format

static void	setField(Class<?> targetClass, String name, Object value)

static void	setField(Class<?> targetClass, String name, Object value, Class<?> type)

static void	setField(Object targetObject, Class<?> targetClass, String name, Object value, Class<?> type)

static void	setField(Object targetObject, String name, Object value)

static void	setField(Object targetObject, String name, Object value, Class<?> type)

Usage Example

@Test
public void testPrivateValue() {
    ReflectionTestUtils.setField(reflectionTestUtilsComponent, "privateValue", 100);
    // ReflectionTestUtils.setField(target object, "variable name", target value);

    Assertions.assertEquals(100, reflectionTestUtilsComponent.getPrivateValue());
}


private Method(Function) Test

Format

static <T> T	invokeMethod(Class<?> targetClass, String name, Object... args)

static <T> T	invokeMethod(Object targetObject, Class<?> targetClass, String name, Object... args)

static <T> T	invokeMethod(Object target, String name, Object... args)

Usage Example

@Test
public void testPrivateMethod() {
    ReflectionTestUtils.setField(reflectionTestUtilsComponent, "privateValue", 100);
    // ReflectionTestUtils.setField(target object, "variable name", target value);

    Assertions.assertEquals(103, (Integer) ReflectionTestUtils.invokeMethod(reflectionTestUtilsComponent, "privateMethod", 1, 2));
    // ReflectionTestUtils.invokeMethod(target object, "method(function) name", arguments);

    Assertions.assertEquals(103, reflectionTestUtilsComponent.getPrivateValue());
}


Github Example


Reference