h2 데이터베이스로 테스트할 때 application.properties에서 아래와 같이 변경(수정해야 하는 부분만 가져옴)
Mockito를 사용하면 DB 안 거치니까 필요없다.
spring.datasource.url=jdbc:h2:tcp://localhost/~/test
spring.datasource.driver-class-name=org.h2.Driver
JUnit 5는 Architecture Jupiter, Vintage, JUnit Platform로 나뉘어 진다.
Jupiter와 Vintage 모두 JUnit Platform을 구현하는 구현체
Jupiter는 JUnit 5의 구현체
@Autowired를 선언하면 Jupiter가 Spring Container에게 빈 주입을 요청
어노테이션
@BeforeAll | 클래스의 모든 메서드를 실행 전에 딱 한 번 실행 static 메소드에 사용 |
@AfterAll | 클래스의 모든 메서드 실행 후에 딱 한 번 실행 static 메소드에 사용 |
@BeforeEach | 클래스의 모든 메서드 실행 전에 실행 |
@AfterEach | 클래스의 모든 메서드 실행 후에 실행 |
@Disabled | 테스트를 하고 싶지 않은 클래스나 메서드에 붙임 |
@DisplayName | 어떤 테스트인지 표현하는 어노테이션(공백, Emoji, 특수문자 등 모두 지원) |
@RepeatedTest | 특정 테스트를 반복시키고 싶을 때 사용(반복 횟수와 반복 테스트 이름을 설정가능) |
@ParameterizedTest | 테스트에 여러 다른 매개변수를 대입해가며 반복 실행할 때 사용 |
@Nested | 테스트 클래스 안에서 내부 클래스를 정의해 테스트를 계층화 내부 클래스는 부모 클래스의 멤버 필드에 접근 가능 |
@BeforeEach, @AfterEach는 매 메서드마다 새로운 클래스를 생성하여 실행하기 때문에 비효율적
JUnit은 각 테스트 메서드 마다 매번 새로운 객체를 생성한다.
@TestInstanceAnnotation | JUnit 5 테스트의 lifecycle을 설정할 수 있다. 테스트 클래스 위에 붙인다. LifeCycle.PER_METHOD : 기본 LifeCycle.PER_CLASS : 오직 하나의 인스턴스만 만들고 테스트간에 재사용한다. |
Assertions
테스트 케이스의 수행 결과를 판별하는 메서드
1. assertAll(executables...)
- 매개변수로 받은 모든 테스트코드를 한번에 실행
- 오류가 나도 끝까지 실행한 뒤 한번에 모아서 출력
@Test
void groupedAssertions() {
// In a grouped assertion all assertions are executed, and all
// failures will be reported together.
assertAll("person",
() -> assertEquals("Jane", person.getFirstName()),
() -> assertEquals("Doe", person.getLastName())
);
}
2. assertThrows(expectedType, executable)
- 예외 발생을 확인
- executable의 로직이 실행하는 도중 expectedType의 에러를 발생시키는지 확인
@Test
void exceptionTesting() {
Exception exception = assertThrows(ArithmeticException.class, () ->
calculator.divide(1, 0));
assertEquals("/ by zero", exception.getMessage());
}
3. assertTimeout(duration, executable)
- 특정 시간 안에 실행이 완료되는지 확인
- Duration : 원하는 시간
- Executable : 테스트할 로직
@Test
void timeoutNotExceeded() {
// The following assertion succeeds.
assertTimeout(ofMinutes(2), () -> {
// Perform task that takes less than 2 minutes.
});
}
Assumption
- 전제문이 true라면 실행, false면 종료
- assumeTrue : false일 때 이후 테스트 전체가 실행되지 않음
- assumingThat : 파라미터로 전달된 코드블럭만 실행되지 않음
참고 👇
https://junit.org/junit5/docs/current/user-guide/#advanced-topics
https://www.youtube.com/watch?v=EwI3E9Natcw
https://ict-nroo.tistory.com/117
https://minkukjo.github.io/framework/2020/06/28/JUnit-23/
https://www.baeldung.com/junit-testinstance-annotation
'Test > Junit' 카테고리의 다른 글
[MockMvc] 테스트 시 redirect 여부 확인 (0) | 2022.09.17 |
---|---|
[MockMvc] Pageable (0) | 2022.09.17 |
[Error] Internal Error occurred. org.junit.platform.commons.JUnitException: TestEngine with ID 'junit-jupiter' failed to discover tests (1) | 2022.09.12 |
Cannot resolve symbol 'WithMockUser' (0) | 2022.08.30 |