[Java] @Nested & @Test Annotation (feat. JUnit )

JAsmine_log·2024년 4월 14일

@ (Annotation)

Java에서 @(어노테이션, Annotation)은 다른 프로그램에 정보를 제공하기 사용하는 것으로, 주석과 같은 의미를 갖는다.

@ 사용

  • Information for the compiler
    — 컴파일러가 에러 감지 또는 주석을 사용해서 경고를 억제한다.

  • Compile-time and deployment

  • 소프트웨어 도구가 어노테이션 정보를 처리해서 코드, XML 파일 등을 생성할 수 있다.
  • Runtime processing
    — 일부 주석은 런타임에 검사할 수 있다.

@예시

@Nested

Junit5에서 코드테스트할 때 사용할 수 있다.
클래스로 비슷함 함수를 묶을 수 있다.

import org.junit.jupiter.api.Nested;

class OrderedNestedTestClassesDemo {

    @Nested
    @Order(1)
    class PrimaryTests {

        @Test
        void test1() {
        }
    }

    @Nested
    @Order(2)
    class SecondaryTests {

        @Test
        void test2() {
        }
    }
}

주석된 클래스 he annotated class is a non-static nested test class.
Java 8부터 15까지는, @BeforeAll와 @AfterAll 메서드는 클래스별 테스트 인스턴스(test instance) 수명 주기(life cycle)가 사용되지 않으면, @Nested 테스트 클래스에서 직접 사용할 수 없었다.
Java 16부터 @BeforeAll 및 @AfterAll 메서드는 테스트 인스턴스 수명 주기 모드를 사용하여 @Nested 테스트 클래스에서 정적으로 선언되고, 상속되지 않는다.

@Test

Junit5에서 코드테스트할 때 사용할 수 있다.

import org.junit.jupiter.api.Test;

@Test
void addition() {
	assertEquals(2, calculator.add(1, 1));
    //assertEquals(expected, actural);
}

Test용 메서드이다. JUnit 4dml @Test 와는 다르게 atrributes의 선언을 하지 않다. 이는 Test extension이 자체 전용 annotation을 기반으로 작동하기 때문이다. 이러한 메서드는 재정의되지 않는 한 상속된다.

Reference

[1] https://docs.oracle.com/javase/tutorial/java/annotations/
[2] https://junit.org/junit5/docs/current/user-guide/#writing-tests-nested

profile
Everyday Research & Development

0개의 댓글