2jigoo / BookStudy-StartTdd

'테스트 주도 개발 시작하기' 스터디
2 stars 0 forks source link

[3주차-2] JUnit 5 기초/ 테스트 코드의 구성 - 2jigoo #16

Closed 2jigoo closed 1 year ago

2jigoo commented 1 year ago

Chapter 5. JUnit 5 기초 / Chapter 6. 테스트 코드의 구성

스터디 일시 2023.08.29

목표

2jigoo commented 1 year ago

Chapter 5. JUnit 5 기초

JUnit 5 모듈 구성

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter'
}

// task test: JUnit 5 플랫폼을 사용하도록 설정
test {
    useJUnitPlatform()
}


@Test 어노테이션과 테스트 메서드


주요 단언 메서드

// 값 비교
assertEquals(expected, actual);
assertNotEquals(unexpected, actual);

// 레퍼런스 비교
assertSame(Object expected, Object actual);
assertNotSame(Object unexpected, Object actual);

assertTrue(boolean condition);
assertFalse(boolean condition);
assertNull(Object actual);
assertNotNull(Object actual);

// 테스트를 실패 처리
fail();


Exception 발생 유무 검사

// executable을 실행한 결과, 지정한 타입의 Exception이 발생하는지 검사
assertThrows(Class<T> expectedType, Executable excutable);

// Exception이 발생하지 않는지 검사
assertDoesNotThrow(Executable executable);
// 발생한 Exception 객체를 리턴
IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () -> {
    AuthService authService = new AuthService();
    authService.authenticate(null, null);
});

// 발생한 Exception을 이용하여 *추가적인 검증*
assertTrue(thrown.getMessage().contains("id"));

Executable

package org.junit.jupiter.api.function;

public interface Executable {
    void execute() throws Throwable;
}

모든 검증을 실행한 후 실패 여부 확인

assertAll(
    () -> assertEquals(3, 5/2),
    () -> assertEquals(4, 2*2),
    () -> assertEquals(6, 11/2)
);


라이프사이클

@BeforeEach, @AfterEach

  1. 테스트 메서드를 포함한 객체 생성 (생성자 호출
    • 테스트 메서드를 실행할 때마다 객체를 새로 생성함
  2. @BeforeEach 메서드 실행
  3. @Test가 붙은 메서드 실행
  4. @AfterEach 메서드 실행

@BeforeAll, @AfterAll


테스트 메서드 간 실행 순서 의존과 필드 공유하지 않기


기타


모든 테스트 실행하기

2jigoo commented 1 year ago

Chapter 6. 테스트 코드의 구성

기능에서의 상황

테스트 코드의 구성 요소: 상황, 실행, 결과 확인

given, when, then


외부 상황과 외부 결과

외부 상태가 테스트 결과에 영향을 주지 않게 하기

외부 상태와 테스트 어려움

예) 금융 회사에서 제공하는 REST API 사용 시, 자동이체 등록 기능