Junit
https://spring.io/guides/gs/testing-web
Getting Started | Testing the Web Layer
You will build a simple Spring application and test it with JUnit. You probably already know how to write and run unit tests of the individual classes in your application, so, for this guide, we will concentrate on using Spring Test and Spring Boot feature
spring.io
주요 내용
- 단위테스트: 특정 소스코드의 모듈이 의도한 대로 잘 작동하는지 검증하는 테스트이다
- JUnit: Java에서 독립된 단위 테스트를 지원해주는 프레임워크이다
- LifeCycle Method: BeforeAll → BeforeEach → Test → AfterEach → AfterAll
사용 버전
- 5.10.1(springboot가 3.2.2)
DB와 연관된 테스트코드의 문제점
연결 안되어있으면 테스트 코드 실패 → 따라서 DB연결이 필요없는 테스트코드들을 한번에 돌리려고 해도 각 단위테스트를 일일히 실행하거나 실제 DB를 연결하지않고 가상의 데이터를 넣어서 불안정하게 DB테스트를 해야한다
Tag분기
https://junit.org/junit5/docs/current/user-guide/#writing-tests-tagging-and-filtering
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
주요내용
- 기존 Junit4의 Category → Junit5 Tag
- @Tag를 이용한 테스트 분기
- 실행시 어떤 태그가 불릴지 설정 및 build.gradle설정에 따라 실행되거나 안되게 할 수 있음
- 배포 상태에서도 문제 없다고 판단
적용 예정 내용
- DB와 연관이 없는 단위 테스트들과 연관 있는 테스트들을 그룹화 시켜 실행 가능
- 통합 테스트 실행시에 포함하지 않을 단위테스트 그룹 추가 가능
적용
태그 적용
- QuestionRepositoryTest.java 등 모든 Test코드
@SpringBootTest
@Transactional
@Tag("db_test")
public class QuesionsRepositoryTest {
@Autowired
private QuestionsService questionsService;
@Autowired
private DriverLicenseQuestionsRepository driverLicenseQuestionsRepository;
...이하 생략
}
태그로 그룹화된 내용 Gradle에 적용
- build.gradle
//기본 테스트시에 포함할 태그와 포함하지 않을 태그 언급
tasks.named('test') {
outputs.dir snippetsDir
useJUnitPlatform(){
includeTags 'basic_test'
excludeTags 'db_test'
}
}
//DB의 영향이 없는 테스트 묶음
task basicTest(type:Test) {
useJUnitPlatform {
includeTags 'basic_test'
}
}
//DB 실행이 필요한 테스트 묶음
task dbTest(type: Test) {
useJUnitPlatform {
includeTags 'db_test'
}
}
테스트 결과
- basicTest
- ExamsControllerTest, QuestionControllerTest
- dbTest
- ExamsRepositoryTest, SubExamRepositoryTest, QuestionRepositoryTest
출처
'스프링 > 테스트' 카테고리의 다른 글
Spring Testcontainer를 활용한 Elasticsearch 테스트 코드 작성 (0) | 2024.04.23 |
---|---|
Postman을 활용한 API 테스트에서의 로그인 세션 유지 및 타 API 테스트 (0) | 2024.04.19 |