JUnit 은 테스트 메소드 마다 테스트 인스턴스를 새로 만든다. (기본 전략)
테스트 메소드를 독립적으로 실행하여 예상치 못한 부작용을 방지하기 위함이다.
class StudyTest {
int value = 1;
@Test
void test1() {
System.out.println(this); // StudyTest@59429fac
System.out.println(value++); // 1
}
@Test
void test2() {
System.out.println(this); // StudyTest@4c03a37
System.out.println(value++); // 1
}
}
테스트 클래스당 인스턴스를 하나만 만들고 공유한다.
경우에 따라, 테스트 간에 공유하는 모든 상태를 @BeforeEach 또는 @AfterEach 에서 초기화할 필요가 있다.
@BeforeAll 과 @AfterAll 을 인스턴스 메소드 또는 인터페이스에 정의한 default 메소드로 정의할 수도 있다.
하나의 인스터스만을 사용하기 때문에 @BeforeAll 과 @AfterAll 을 static 키워드로 정의할 필요가 없다.
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class StudyTest {
int value = 1;
@Test
void test1() {
System.out.println(this); // StudyTest@4e423aa2
System.out.println(value++); // 1
}
@Test
void test2() {
System.out.println(this); // StudyTest@4e423aa2
System.out.println(value++); // 2
}
@BeforeAll
void beforeAll() {
System.out.println("before all");
}
@AfterAll
void afterAll() {
System.out.println("after all");
}
}