
단위 테스트(Unit Test) 는 애플리케이션의 가장 작은 단위(클래스, 메서드)를 독립적으로 테스트하는 과정입니다. 개발자가 작성한 코드가 기대한 대로 동작하는지 확인하며, 주로 하나의 특정 기능에 초점을 맞춥니다.
단위 테스트의 주요 목적:
먼저, 수동 테스트로 단위 테스트를 시도해보겠습니다. 아래는 간단한 수동 테스트 코드입니다:
@Test
void parkVehicle() {
ParkingLotSystem parkingLotSystem = new ParkingLotSystem();
parkingLotSystem.parkVehicle(new Vehicle("ABC-1234"));
// 결과를 사람이 직접 확인
System.out.println(">>> 주차된 차량 수: " + parkingLotSystem.getVehicles().size());
System.out.println(">>> 주차된 차량 번호: " + parkingLotSystem.getVehicles().get(0).getLicensePlate());
}
수동 테스트의 과정:
1. 테스트 코드를 실행합니다.
2. System.out.println을 통해 출력된 결과를 사람이 직접 확인합니다.
문제점:
수동 테스트의 비효율성을 해결하기 위해, 자동화된 테스트를 사용합니다. 자동화된 테스트는 다음과 같은 장점을 제공합니다:
아래는 JUnit5와 AssertJ를 사용하여 동일한 테스트를 자동화한 코드입니다:
@Test
@DisplayName("주차 자동 테스트")
void parkVehicle() {
ParkingLotSystem parkingLotSystem = new ParkingLotSystem();
parkingLotSystem.parkVehicle(new Vehicle("XYZ-5678"));
// AssertJ를 활용하여 자동으로 결과 검증
assertThat(parkingLotSystem.getVehicles()).hasSize(1);
assertThat(parkingLotSystem.getVehicles().get(0).getLicensePlate()).isEqualTo("XYZ-5678");
}
JUnit5와 AssertJ는 자바 기반의 테스트 환경에서 널리 사용되는 도구입니다. 각각의 역할과 기본 사용법은 다음과 같습니다.
@Test: 테스트 메서드로 선언.@BeforeEach: 각 테스트 실행 전 초기화 작업.@AfterEach: 각 테스트 실행 후 정리 작업.@BeforeEach
void setUp() {
parkingLotSystem = new ParkingLotSystem();
}
@Test
void parkVehicle() {
parkingLotSystem.parkVehicle(new Vehicle("LMN-9012"));
assertThat(parkingLotSystem.getVehicles()).hasSize(1);
}
assertThat 메서드를 통해 직관적으로 검증 가능.@Test
void assertJExample() {
List<String> vehicles = List.of("DEF-3456", "JKL-7890");
assertThat(vehicles)
.hasSize(2) // 리스트 크기 검증
.contains("DEF-3456") // 특정 값 포함 여부 검증
.doesNotContain("MNO-1111"); // 특정 값 미포함 여부 검증
}
📌 이 글은 TDD 강의를 학습한 내용을 바탕으로 재구성하였습니다. 문제가 되는 부분이 있다면 수정하겠습니다.