추가 애너테이션

Java 테스트 소개

Maria Milusheva

Senior Software Engineer

.of()로 객체 생성: 사전 지식

다음을 보십시오:

List<Integer> newList = new ArrayList<Integer>();
newList.add(10);
newList.add(20);
newList.add(30);

더 빠르고 짧은 방식:

List<Integer> newList = List.of(10, 20, 30);
  • Java Collections의 Set, Map에도 동일하게 적용됨

  • .of()로 만든 객체는 보통 불변(변경 불가)임

Java 테스트 소개

객체를 @ParameterizedTest에 전달

다음 클래스를 보십시오:

class Person {
    String firstName;
    String lastName;
    public Person(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
    public String fullName(Person person) {
        return firstName + " " + lastName;
    }
}
Java 테스트 소개

Arguments 클래스

여러 타입의 인자를 전달하려면 Arguments를 사용합니다.

Arguments는 어떤 종류의 객체든 여러 개를 담을 수 있습니다.

예:

Arguments.of(new Person("Monty", "Python"), "Monty Python");

이제 다음 @ParameterizedTest 유형에서 사용할 수 있습니다.

Java 테스트 소개

@MethodSource

@MethodSource는 어떤 객체든 테스트에 전달할 수 있게 합니다.

테스트는 다음과 같습니다:

@ParameterizedTest
@MethodSource("provideNames")
void testFullName(Person person, String expectedFullName) {
    assertEquals(person.fullName(person), expectedFullName);
}
Java 테스트 소개

@MethodSource 제공 메서드

@MethodSource용 메서드:

private static List<Arguments> provideNames() {
    List<Arguments> args = new ArrayList<>();
    args.add(Arguments.of(new Person("Robert", "Martin"), "Robert Martin"));
    args.add(Arguments.of(new Person("Heinz", "Kabutz"), "Heinz Kabutz"));

    return args;
}

참고: 메서드는 static이어야 함

참고: 반환 타입은 여러 가지 허용되며 List<Arguments>가 가장 간단함

1 https://junit.org/junit5/docs/5.2.0/api/org/junit/jupiter/params/provider/MethodSource.html
Java 테스트 소개

@MethodSource 제공 메서드

@MethodSource용 메서드:

private static List<Arguments> provideNames() {
    return List.of(
        Arguments.of(new Person("John", "Doe"), "John Doe"),
        Arguments.of(new Person("Jane", "Doe"), "Jane Doe"),
        Arguments.of(new Person("Alice", "Bob"), "Alice Bob"));
}
Java 테스트 소개

인자 외에 더 필요하면?

다음 데이터베이스 테스트를 보십시오:

@Test
void process_savesToInfoStore_whenInfoMessage() {
  InfoStore infoStore = mock(InfoStore.class);
  ErrorStore errorStore = mock(ErrorStore.class);
  MessageProcessor messageProcessor = new MessageProcessor(infoStore, errorStore);

messageProcessor.saveMessage("[INFO] Process started.");
verify(infoStore).save("[INFO] Process started."); verifyNoInteractions(errorStore); }
Java 테스트 소개

@BeforeEach 애너테이션

각 테스트 전에 실행되는 메서드를 만들려면 @BeforeEach 애너테이션을 사용합니다:

import org.junit.jupiter.api.BeforeEach;

사용하려면 먼저 객체를 필드로 선언합니다:

class MessageProcessorTest {

    private InfoStore infoStore;
    private ErrorStore errorStore;
    private MessageProcessor messageProcessor;
Java 테스트 소개

@BeforeEach용 메서드

각 객체를 별도 메서드에서 생성합니다:

@BeforeEach
void setUp() {
    this.infoStore = mock(InfoStore.class);
    this.errorStore = mock(errorStore.class);
    this.messageProcessor = new MessageProcessor(infoStore, errorStore);
}
Java 테스트 소개

축약된 테스트

그렇다면 테스트 클래스는 다음과 같습니다:

@Test
void process_savesToInfoStore_whenInfoMessage() {
    messageProcessor.process("[INFO] Process started.");

    verify(infoStore).save("[INFO] Process started."); 
    verifyNoInteractions(errorStore); 
}
Java 테스트 소개

@BeforeEach 전체 흐름

모두 합치면:

class MessageProcessorTest {
    private InfoStore infoStore; // 필드 선언


@BeforeEach void setUp() { this.infoStore = mock(InfoStore.class); // 필드 초기화 }
@Test void process_savesToInfoStore_whenInfoMessage() { // 필드 사용 } }
Java 테스트 소개

Ayo berlatih!

Java 테스트 소개

Preparing Video For Download...