주관적인 내용이 들어가 있습니다.
public class Car {
public void move() { … }
}
// 컴파일 타임에 Object라는 타입이 결정됨
// Object 클래스의 인스턴스 변수와 메서드만 사용할 수 있다.
// 따라서 컴파일 에러 발생한다.
Object obj = new Car();
obj.move();
// Reflection API 사용
Object obj = new Car();
Class carClass = Car.class;
Method move. = carClass.getMethod(“move”);
// move 메서드 실행
// invoke(메서드를 실행시킬 객체, 메소드 파리미터)
move.invoke(obj, null);
자바에서는 JVM이 실행되면 사용자가 작성한 자바 코드가 컴파일러를 거쳐 바이트 코드로 변환되어 static 영역에 저장된다. Reflection API는 이 정보를 활용한다. 그래서 클래스 이름만 알고 있다면 언제든 static 영역을 뒤져서 정보를 가져올 수 있는 것이다.
Method maxMethod = Calculator.class.getDeclaredMethod("max", int.class, int.class);
maxMethod.setAccessible(true);
int source = 10;
int target = 5;
int maxValue = (int)maxMethod.invoke(calculator, source, target);
getMethod(String name, Class<?>... parameterTypes)
public 메소드, superclasses 와 superinterface 의 메소드 전부 가져올 수 있다.
getDeclaredMethod(String name, Class<?>... parameterTypes)
해당 클래스에만 선언된 메소드만 가져올 수 있다.
Junit 5
@Parameterized
하나의 테스트 메서드로 여러개의 파라미터에 대해서 테스트할 수 있다.
최소 하나의 source 어노테이션을 붙여주어야 한다.
@ValueSource
단일 배열을 지정할 수 있으며 매개 변수화 된 테스트 호출마다 단일 인수를 제공하는 데만 사용
@ParameterizedTest
@ValueSource(strings = {"q", "qwerasdfzxcv", "qq23"})
void createUserException(String name){
IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> new User(VALID_EMAIL, name, password));
assertThat(e.getMessage()).isEqualTo(NAME_NOT_MATCH_MESSAGE);
}
@ParameterizedTest
@NullSource
@EmptySource
void nullEmptyStrings(String text) {
assertTrue(text == null || text.trim().isEmpty());
}
@ParameterizedTest
@NullAndEmptySource
@ValueSource(strings = { " ", " ", "\t", "\n" })
void nullEmptyAndBlankStrings(String text) {
assertTrue(text == null || text.trim().isEmpty());
}
@ParameterizedTest
@MethodSource("invalidParameters")
void invalidCreate(String name, String email, String password, String message, String exceptionMessage) {
IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> new User(email, name, password));
assertThat(e.getMessage()).isEqualTo(exceptionMessage);
}
static Stream<Arguments> invalidParameters() throws Throwable {
return Stream.of(
Arguments.of("a", VALID_EMAIL, VALID_PASSWORD, "name 2자 미만", NAME_NOT_MATCH_MESSAGE),
Arguments.of("qwertasdfzpl", VALID_EMAIL, VALID_PASSWORD, "name 10자 초과", NAME_NOT_MATCH_MESSAGE));
}