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
JUnit 5 User Guide
Although the JUnit Jupiter programming model and extension model do not support JUnit 4 features such as Rules and Runners natively, it is not expected that source code maintainers will need to update all of their existing tests, test extensions, and custo
junit.org
https://www.youtube.com/watch?v=EwI3E9Natcw
https://ict-nroo.tistory.com/117
[JPA] Spring Data JPA와 QueryDSL 이해, 실무 경험 공유
Spring Data JPA와 QueryDSL JPA 기반 프로젝트 Spring Data JPA QueryDSL Spring Data JPA 지루하게 반복되는 CRUD 문제를 세련된 방법으로 해결 개발자는 인터페이스만 작성한다 스프링 데이터 JPA가 구현 객체..
ict-nroo.tistory.com
[Spring] 회원 서비스 테스트
그냥 질문 글 정리 테스트를 위한 객체를 생성하고 각 테스트를 할 때 마다 memoryRepository를 clear해주면 된다고 생각을 했다. 그런데 강의 코드는 테스트 시작 전 마다 계속 새로운 객체를 생성해
velog.io
https://minkukjo.github.io/framework/2020/06/28/JUnit-23/
JUnit 5 + Kotlin 테스트 클래스에서 생성자 주입 이슈
서론
minkukjo.github.io
https://www.baeldung.com/junit-testinstance-annotation
@TestInstance Annotation in JUnit 5 | Baeldung
JUnit 5 allows us to customise the lifecycle of our test objects to share resources and state between tests. We investigate the @TestInstance annotation.
www.baeldung.com
'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 |