NoArgsConstructor의 접근 제어자는 protected
- for jpa, mybatis, controller mapping...
Anti Setter 전략을 선호
이러한 환경 속에서 테스트 코드를 작성하자!
Service단의 테스트 코드 작성시,
Class<?> clazz = Class.forName(kr.co.example.MyClass);
Constructor<?> constructor = clazz.getDeclaredConstructor();
//getConstructor()는 public에만 접근 가능
//parameter가 있는 경우,
//Constructor<?> constructor = clazz.getDeclaredConstructor(parameterType.class);
constructor.setAccessible(true); //접근 제어자 강제 변경
MyClass myClass = (MyClass)constructor.newInstance();
ReflectionTestUtils.setField(myClass, "fieldName", "value");
Field field = ReflectionUtils.findField(MyClass.class, "fieldName");
field.setAccessible(true);
ReflectionUtils.setField(field, myClass, "value");
Method method = ReflectionUtils.findMethod(MyClass.class, "methodName");
//Method method = ReflectionUtils.findMethod(MyClass.class, "methodName", "parameter")
.get();
field.setAccessible(true);
ReflectionUtils.setField(field, myClass, String.class)//마지막 param은 메서드의 parameter type
.get();
Result result = ReflectionUtils.invokeMethod(method, myClass);