본문 바로가기
Spring/Spring-detail

JUnit 테스트의 생명주기를 알아보자

by YoonJong 2022. 9. 11.
728x90

JUnit의 생명주기를 확인해본다.

 

@Test : 테스트 코드를 포함한 메서드를 정의한다.

@BeforeAll : 테스트를 시작하기 전에 호출되는 메서드를 정의한다.

@BeforeEach : 각 테스트 메서드가 실행되기 전에 동작하는 메서드를 정의한다.

@AfterAll : 테스트를 종료하면서 호출되는 메서드를 정의한다.

@AfterEach : 각 테스트 메서드가 종료되면서 호출되는 메서드를 정의한다.

 

아래 전체 코드를 통해 확인해보자.

public class TestLifeCycle {

    @BeforeAll
    static void beforeAll() {
        System.out.println("## BeforeAll Annotation 호출 ##");
        System.out.println();
    }

    @AfterAll
    static void afterAll() {
        System.out.println("## AfterAll Annotation 호출 ##");
        System.out.println();
    }

    @BeforeEach
    void beforeEach() {
        System.out.println("## BeforeEach Annotation 호출 ##");
        System.out.println();
    }

    @AfterEach
    void afterEach() {
        System.out.println("## AfterEach Annotation 호출 ##");
        System.out.println();
    }

    @Test
    void test1() {
        System.out.println("## test1 시작 ##");
        System.out.println();
    }

    @Test
    @DisplayName("Test Case 2!!!")
    void test2() {
        System.out.println("## test2 시작 ##");
        System.out.println();
    }

    @Test
    @Disabled
    void test3 () {
        System.out.println("## test3 시작 ##");
        System.out.println();
    }
}

 

 

 


출력결과

## BeforeAll Annotation 호출 ##

## BeforeEach Annotation 호출 ##

## test1 시작 ##

## AfterEach Annotation 호출 ##

## BeforeEach Annotation 호출 ##

## test2 시작 ##

## AfterEach Annotation 호출 ##


void com.springboot.TestLifeCycle.test3() is @Disabled
## AfterAll Annotation 호출 ##


종료 코드 0(으)로 완료된 프로세스

 

 

기존에 @BeforeAll 과 @AtferAll 을 따로 사용해본적이 없는데, 해당 게시물을 정리하면서 확인할 수 있었다.

 

두개의 어노테이션에는 static을 붙여주어야 한다.

붙이지 않으면 아래와 같이 사용이 안되는 표시가 되며, static 을 붙여야 정상적으로 작동한다.

 

에러코드를 확인하면 static 이 꼭 필요하다고 표시해준다.

 

728x90

'Spring > Spring-detail' 카테고리의 다른 글

좋은 객체 지향 설계의 5가지 원칙(SOLID)  (0) 2022.09.14
JPA Auditing 적용  (0) 2022.09.13
application.yml 에서 JPA 설정하기  (1) 2022.09.11
Spring Security H2 DB 접근하기  (0) 2022.09.02
ResponseEntity<T>  (0) 2022.08.31

댓글