JUnit 사용할 때, 허갈리는 전역변수와 @BeforeEach, @BeforeAll 에 대해서 알아보자.
요약 :
전역변수는 @BeforeEach의 효과
@BeforeEach는 각 테스트 함수가 불리기 전에 매번 호출 됨(JUnit4에서 @Before)
@BeforeAll은 테스트 함수가 불리기 전에 딱 한 번 호출 됨(JUnit4에서 @BeforeClass)
출처 : https://junit.org/junit5/docs/current/user-guide/#writing-tests-annotations
+
이제.. 실제로 그런지 확인해 봅시다.
IntelliJ에서 원하는 함수를 선택하고 Generate를 선택하면 Test 메뉴가 보입니다.
그럼 아래 처럼 팝업이 뜨게 될 겁니다. OK 선택하시고.
원하면 여러 함수를 선택하셔도 됩니다.
그럼 아래와 같이 코드가 나오는데요.
package com.company;
import static org.junit.jupiter.api.Assertions.*;
class SolutionTest {
@org.junit.jupiter.api.Test
void reorderLogFiles() {
}
}
아래 처럼 바꿔 주셔도 됩니다.
// 아래처럼 import 좀 손봐주면 '@Test' 를 바로 쓸 수 있습니다.
// 또한, assertEquals() 함수를 바로 쓸 수 있습니다.
package com.company;
import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertEquals;
class SolutionTest {
@Test
void reorderLogFiles() {
}
}
그리고 제가 적은 요약 부분을 상기 하면서 아래 코드를 확인 하시면 됩니다.
아래 코드는 요약 부분이 맞는지 확인하는 코드이며, 큰 의미 없습니다.(Test2, Test1 순으로 실행 되었네요.)
package com.company;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertEquals;
class SolutionTest {
// Test 함수가 호출 되기 전에 매번 호출 됩니다.
@BeforeEach // @Before in Junit 4
public void setupEveryTime(){
logs = new String[]{"j mo", "5 m w", "g 07", "o 2 0", "t q h"};
System.out.println("@BeforeEach is called every time");
}
// 전역 변수는 @BeforeEach 와 같은 효과가 있어서 매번 호출 됩니다.
Solution solution = new Solution();
String[] logs;
int value = 1; // 매번 호출 된다.
@BeforeAll
public static void setupOnlyOnce(){
System.out.println("@BeforeAll is called only once");
}
@Test
void Test_example_test1_reorderLogFiles() {
System.out.println("value in test = " + value);
value = 0;
// assertEquals(true, solution.reorderLogFiles(logs));
}
@Test
void Test_example_test2_reorderLogFiles() {
System.out.println("value in test2 = " + value);
// value = 1
// 전역변수는 @BeforeEach 효과가 있어서, test1의 영향 받지 않는다.
// assertEquals(true, solution.reorderLogFiles(logs));
}
}
아래는 실행 결과 입니다.
@BeforeAll is called only once
@BeforeEach is called every time
value in test2 = 1
@BeforeEach is called every time
value in test = 1
Process finished with exit code 0
전역변수와 @BeforeEach, @BeforeAll 에 대해서 알아 보았습니다.
그럼 즐공~
출처 : https://developyo.tistory.com/172
https://epthffh.tistory.com/entry/Junit을-이용한-단위테스트
https://lee-mandu.tistory.com/398?category=633568
https://junit.org/junit5/docs/current/user-guide/#writing-tests-annotations