chore: 테스트 계약 생성 support

This commit is contained in:
DongHyeonka
2026-09-21 11:30:05 +09:00
parent 70d71008c6
commit 62bc656c08
28 changed files with 1989 additions and 164 deletions
@@ -5,7 +5,6 @@ import java.time.LocalDate;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.springframework.data.domain.Page;
@@ -0,0 +1,220 @@
package com.study.course_registration.controller;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.DayOfWeek;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalTime;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.MockMvc;
import com.study.course_registration.entity.Lesson;
import com.study.course_registration.entity.LessonSchedule;
import com.study.course_registration.entity.Professor;
import com.study.course_registration.entity.Semester;
import com.study.course_registration.entity.Subject;
import com.study.course_registration.entity.User;
import com.study.course_registration.enums.RegistrationErrorCode;
import com.study.course_registration.enums.UserRole;
import com.study.course_registration.repository.LessonRepository;
import com.study.course_registration.repository.LessonScheduleRepository;
import com.study.course_registration.repository.ProfessorRepository;
import com.study.course_registration.repository.SemesterRepository;
import com.study.course_registration.repository.SubjectRepository;
import com.study.course_registration.repository.UserLessonRepository;
import com.study.course_registration.repository.UserRepository;
import com.study.course_registration.support.Rejections;
import com.study.course_registration.support.Scenario;
import com.study.course_registration.support.http.ApiError;
import com.study.course_registration.support.http.JsonApi;
import com.study.course_registration.support.http.JsonBody;
/**
* HTTP 계층. 서비스가 올바른 예외를 던지는 것과, 그게 올바른 상태코드·바디로 나가는 것은 다른 문제다.
* 여기서만 확인할 수 있는 것이 후자다.
*
* <p>표현법은 단위·통합 계층과 같다. {@code Scenario.given(...).when(...).then(...)}.
* HTTP 응답을 {@link ApiError}로 번역하는 일은 {@link JsonApi}가 한다.
*/
@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("test")
@DisplayName("수강신청 API — 에러 코드가 선언된 상태코드로 나가는가")
class CourseRegistrationApiTest {
/**
* HTTP 계층의 거부 판정. 코드를 꺼내면서 <em>그 코드가 선언한 상태코드로 나갔는지</em>도 함께 본다.
* 매핑표는 이미 {@link RegistrationErrorCode}에 있으므로, 테스트는 코드만 적으면 상태코드까지 검증된다.
*/
private static final Rejections<ApiError, RegistrationErrorCode> API =
Rejections.of(ApiError.class, CourseRegistrationApiTest::errorCodeOf);
@Autowired MockMvc mockMvc;
@Autowired UserLessonRepository userLessonRepository;
@Autowired LessonScheduleRepository lessonScheduleRepository;
@Autowired LessonRepository lessonRepository;
@Autowired SubjectRepository subjectRepository;
@Autowired ProfessorRepository professorRepository;
@Autowired SemesterRepository semesterRepository;
@Autowired UserRepository userRepository;
private JsonApi api;
private User student;
private Lesson lesson;
private Subject subject;
@BeforeEach
void setUp() {
userLessonRepository.deleteAll();
lessonScheduleRepository.deleteAll();
lessonRepository.deleteAll();
subjectRepository.deleteAll();
professorRepository.deleteAll();
semesterRepository.deleteAll();
userRepository.deleteAll();
Instant now = Instant.now();
Semester semester = semesterRepository.save(new Semester("semester", "2026-1",
LocalDate.now().minusDays(1), LocalDate.now().plusDays(100),
now.minusSeconds(3600), now.plusSeconds(3600), 18));
Professor professor = professorRepository.save(new Professor("professor", "교수"));
subject = subjectRepository.save(new Subject("subject-a", "과목A", "A101", "A", 3));
student = userRepository.save(new User("user", "학생", 2L, UserRole.STUDENT));
lesson = lessonRepository.save(new Lesson("lesson-a", "강의A", subject, professor, semester, 30, null, null));
lessonScheduleRepository.save(new LessonSchedule("schedule-a", lesson,
DayOfWeek.MONDAY, LocalTime.of(9, 0), LocalTime.of(11, 0)));
api = new JsonApi(mockMvc);
}
@Test
@DisplayName("신청에 성공하면 201과 신청 정보를 돌려준다")
void registerReturnsCreated() {
JsonBody body = Scenario.given(api)
.when(a -> a.post(path(student.getId()), json(lesson.getId())))
.thenAccepted();
assertThat(body.status())
.as("신청 성공은 201이다")
.isEqualTo(201);
// 응답 스키마 전체를 고정한다. 값 몇 개만 보면 필드 이름이 바뀌어도 통과한다.
assertThat(body.fieldNames())
.as("응답 필드 이름은 클라이언트와의 계약이다")
.containsExactlyInAnyOrder(
"registrationId", "userId", "lessonId", "lessonName",
"subjectCode", "credit", "registeredAt", "totalCredits");
assertThat(body.<String>at("$.userId")).isEqualTo(student.getId());
assertThat(body.<String>at("$.lessonId")).isEqualTo(lesson.getId());
assertThat(body.<String>at("$.lessonName")).isEqualTo(lesson.getName());
assertThat(body.<String>at("$.subjectCode")).isEqualTo(subject.getCode());
assertThat(body.<Integer>at("$.credit")).isEqualTo(3);
assertThat(body.<Integer>at("$.totalCredits")).isEqualTo(3);
assertThat(body.<String>at("$.registrationId")).isNotBlank();
assertThat(body.<String>at("$.registeredAt")).isNotBlank();
}
@Test
@DisplayName("취소에 성공하면 204와 빈 본문을 돌려준다")
void cancelReturnsNoContent() {
JsonBody created = api.post(path(student.getId()), json(lesson.getId()));
String registrationId = created.at("$.registrationId");
JsonBody body = Scenario.given(api)
.when(a -> a.delete(path(student.getId()) + "/" + registrationId))
.thenAccepted();
assertThat(body.status())
.as("취소 성공은 204다")
.isEqualTo(204);
assertThat(body.raw())
.as("204에는 본문이 없다")
.isEmpty();
}
@Test
@DisplayName("없는 사용자로 신청하면 USER_NOT_FOUND — 404로 나간다")
void unknownUserIsNotFound() {
Scenario.given(api)
.when(a -> a.post(path("no-such-user"), json(lesson.getId())))
.thenRejectedWith(API, RegistrationErrorCode.USER_NOT_FOUND);
}
@Test
@DisplayName("없는 강의로 신청하면 LESSON_NOT_FOUND — 404로 나간다")
void unknownLessonIsNotFound() {
Scenario.given(api)
.when(a -> a.post(path(student.getId()), json("no-such-lesson")))
.thenRejectedWith(API, RegistrationErrorCode.LESSON_NOT_FOUND);
}
@Test
@DisplayName("같은 강의를 두 번 신청하면 ALREADY_REGISTERED — 409로 나간다")
void duplicateRegistrationIsConflict() {
api.post(path(student.getId()), json(lesson.getId()));
Scenario.given(api)
.when(a -> a.post(path(student.getId()), json(lesson.getId())))
.thenRejectedWith(API, RegistrationErrorCode.ALREADY_REGISTERED);
}
@Test
@DisplayName("lessonId가 비면 VALIDATION_ERROR — 400으로 나간다")
void blankLessonIdIsBadRequest() {
Scenario.given(api)
.when(a -> a.post(path(student.getId()), json("")))
.thenRejectedWith(API, RegistrationErrorCode.VALIDATION_ERROR);
}
@Test
@DisplayName("본문이 JSON이 아니면 VALIDATION_ERROR — 400으로 나간다")
void malformedBodyIsBadRequest() {
Scenario.given(api)
.when(a -> a.post(path(student.getId()), "{not json"))
.thenRejectedWith(API, RegistrationErrorCode.VALIDATION_ERROR);
}
@Test
@DisplayName("없는 신청 건을 취소하면 REGISTRATION_NOT_FOUND — 404로 나간다 (C1)")
void cancelingUnknownRegistrationIsNotFound() {
Scenario.given(api)
.when(a -> a.delete(path(student.getId()) + "/no-such-registration"))
.thenRejectedWith(API, RegistrationErrorCode.REGISTRATION_NOT_FOUND);
}
@Test
@DisplayName("에러 응답 본문은 code·message·timestamp 세 필드를 담는다")
void errorBodyShape() {
ApiError error = org.assertj.core.api.Assertions.catchThrowableOfType(ApiError.class,
() -> api.post(path("no-such-user"), json(lesson.getId())));
assertThat(error.code()).isEqualTo("USER_NOT_FOUND");
assertThat(error.detail()).isNotBlank();
assertThat(error.status()).isEqualTo(404);
}
private static String path(String userId) {
return "/api/v1/users/" + userId + "/registrations";
}
private static String json(String lessonId) {
return "{\"lessonId\": \"" + lessonId + "\"}";
}
/** 코드를 꺼내면서 상태코드 매핑까지 확인한다. HTTP 계층에서만 볼 수 있는 값을 놓치지 않기 위해서다. */
private static RegistrationErrorCode errorCodeOf(ApiError error) {
RegistrationErrorCode code = RegistrationErrorCode.valueOf(error.code());
assertThat(error.status())
.as("%s 는 %s 로 나가야 한다", code, code.getStatus())
.isEqualTo(code.getStatus().value());
return code;
}
}
@@ -0,0 +1,197 @@
package com.study.course_registration.service.policy;
import java.time.DayOfWeek;
import java.time.Instant;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.study.course_registration.entity.Lesson;
import com.study.course_registration.entity.LessonSchedule;
import com.study.course_registration.entity.Semester;
import com.study.course_registration.entity.User;
import com.study.course_registration.entity.UserLesson;
import com.study.course_registration.enums.UserRole;
/**
* 수강신청 도메인의 given 조립 + when 행동. 도메인 지식은 전부 여기 모인다.
*
* <p>given/when/then의 <em>틀</em>은 {@link com.study.course_registration.support.Scenario}가 들고 있고,
* 이 클래스는 그 틀에 넣을 <em>내용</em>만 안다. 도메인이 늘어나면 이 파일이 아니라
* 새 도메인용 Fixture가 하나 더 생긴다.
*
* <p>R1~R8 테스트는 전부 "어떤 학생이 / 어떤 학기에 / 이미 무엇을 신청한 상태로 / 무엇을 신청한다"는
* 같은 뼈대를 쓴다. 규칙마다 그중 한두 칸만 달라지므로, 뼈대는 여기에 두고 테스트에는 달라지는 칸만 적는다.
*
* <p>when 단계는 {@link #checkEligibility()} / {@link #register()} 두 개다.
* 예외를 잡는 일은 {@code Scenario.when(...)}이 하므로 여기서는 그냥 던진다.
*/
final class RegistrationFixture {
private static final String CANDIDATE_LESSON_ID = "lesson-b";
private static final String EXISTING_LESSON_ID = "lesson-a";
private final RegistrationValidator validator = new RegistrationValidator(new ScheduleConflictChecker());
private Semester semester = TestFixtures.semester(18);
private final long grade;
private String candidateSubjectId = "subject-b";
private int candidateCredit = 3;
private int capacity = 30;
private Long minGrade;
private UserRole allowedRole;
private Slot candidateSlot;
private boolean existingIsSameLesson;
private String existingSubjectId;
private int existingCredit = 3;
private Slot existingSlot;
private long enrolledCount = 1;
private RegistrationFixture(long grade) {
this.grade = grade;
}
/** given: N학년 학부생. 모든 시나리오의 시작점이다. */
static RegistrationFixture student(long grade) {
return new RegistrationFixture(grade);
}
/** given: 학점 상한이 N인 학기 (기본 18) */
RegistrationFixture semesterWithMaxCredits(int maxCredits) {
this.semester = TestFixtures.semester(maxCredits);
return this;
}
/** given: 신청 기간이 이미 끝난 학기 */
RegistrationFixture inClosedSemester() {
this.semester = TestFixtures.closedSemester();
return this;
}
/** given: 신청하려는 강의의 과목과 학점 (기본 subject-b / 3학점) */
RegistrationFixture applyingFor(String subjectId, int credit) {
this.candidateSubjectId = subjectId;
this.candidateCredit = credit;
return this;
}
/** given: 신청하려는 강의에 걸린 최소 학년 제한 */
RegistrationFixture requiringMinGrade(long minGrade) {
this.minGrade = minGrade;
return this;
}
/** given: 신청하려는 강의에 걸린 역할 제한 */
RegistrationFixture requiringRole(UserRole role) {
this.allowedRole = role;
return this;
}
/** given: 신청하려는 강의의 정원 (기본 30) */
RegistrationFixture withCapacity(int capacity) {
this.capacity = capacity;
return this;
}
/** given: 신청하려는 강의의 현재 유효 신청 수 (기본 1) */
RegistrationFixture alreadyEnrolled(long enrolledCount) {
this.enrolledCount = enrolledCount;
return this;
}
/** given: 신청하려는 강의의 수업 시간 */
RegistrationFixture scheduledOn(DayOfWeek day, int startHour, int endHour) {
this.candidateSlot = new Slot(day, startHour, endHour);
return this;
}
/** given: 지금 신청하려는 바로 그 강의를 이미 신청해 둔 상태 (R4) */
RegistrationFixture alreadyRegisteredSameLesson() {
this.existingIsSameLesson = true;
return this;
}
/** given: 다른 강의를 이미 신청해 둔 상태. 과목 코드가 같으면 같은 과목의 다른 분반이 된다 (R5) */
RegistrationFixture alreadyRegistered(String subjectId, int credit) {
this.existingSubjectId = subjectId;
this.existingCredit = credit;
return this;
}
/** given: 이미 신청해 둔 강의의 수업 시간 */
RegistrationFixture alreadyRegisteredOn(DayOfWeek day, int startHour, int endHour) {
this.existingSlot = new Slot(day, startHour, endHour);
return this;
}
/** when: 신청 기간·학년·역할만 보는 사전 검사 (R1~R3). 값이 없는 행동이라 자기 자신을 돌려준다. */
RegistrationFixture checkEligibility() {
return checkEligibilityAt(TestFixtures.NOW);
}
/** when: 특정 시각 기준으로 사전 검사 */
RegistrationFixture checkEligibilityAt(Instant now) {
Fixture fixture = assemble();
validator.validatePreconditions(fixture.user(), fixture.candidate(), now);
return this;
}
/** when: 락을 잡은 뒤의 본 검사 — 중복·시간표·학점·정원 (R4~R8) */
RegistrationFixture register() {
Fixture fixture = assemble();
validator.validateLocked(
fixture.candidate(), fixture.existingRegistrations(), fixture.schedules(), enrolledCount);
return this;
}
/** 신청이 성사됐을 때의 누적 학점 */
int totalCreditsAfter() {
Fixture fixture = assemble();
return validator.totalCreditsAfter(fixture.candidate(), fixture.existingRegistrations());
}
Instant registrationEndAt() {
return semester.getRegistrationEndAt();
}
private Fixture assemble() {
User user = TestFixtures.student("user", grade);
Lesson candidate = TestFixtures.lesson(CANDIDATE_LESSON_ID,
TestFixtures.subject(candidateSubjectId, candidateCredit), semester, capacity, minGrade, allowedRole);
List<UserLesson> existingRegistrations = new ArrayList<>();
Map<String, List<LessonSchedule>> schedules = new LinkedHashMap<>();
if (candidateSlot != null) {
schedules.put(candidate.getId(), List.of(candidateSlot.toSchedule("schedule-b", candidate)));
}
if (existingIsSameLesson) {
existingRegistrations.add(TestFixtures.registration("reg", user, candidate));
} else if (existingSubjectId != null) {
Lesson existingLesson = TestFixtures.lesson(EXISTING_LESSON_ID,
TestFixtures.subject(existingSubjectId, existingCredit), semester, 30, null, null);
existingRegistrations.add(TestFixtures.registration("reg", user, existingLesson));
if (existingSlot != null) {
schedules.put(existingLesson.getId(), List.of(existingSlot.toSchedule("schedule-a", existingLesson)));
}
}
return new Fixture(user, candidate, existingRegistrations, schedules);
}
private record Slot(DayOfWeek day, int startHour, int endHour) {
LessonSchedule toSchedule(String id, Lesson lesson) {
return TestFixtures.schedule(id, lesson, day, startHour, endHour);
}
}
private record Fixture(User user,
Lesson candidate,
List<UserLesson> existingRegistrations,
Map<String, List<LessonSchedule>> schedules) {
}
}
@@ -1,163 +1,171 @@
package com.study.course_registration.service.policy;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.time.DayOfWeek;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import com.study.course_registration.entity.Lesson;
import com.study.course_registration.entity.LessonSchedule;
import com.study.course_registration.entity.Semester;
import com.study.course_registration.entity.Subject;
import com.study.course_registration.entity.User;
import com.study.course_registration.entity.UserLesson;
import com.study.course_registration.enums.RegistrationErrorCode;
import com.study.course_registration.enums.UserRole;
import com.study.course_registration.exception.RegistrationException;
import com.study.course_registration.support.Rejections;
import com.study.course_registration.support.Scenario;
/**
* given → when → then 세 단계를 전부 {@link Scenario}에 맡긴다.
*
* <p>이 파일에서 도메인에 묶인 것은 아래 {@code REJECTIONS} 상수 한 줄과, given에 적는 조건뿐이다.
* 나머지 흐름은 어떤 도메인 테스트에서도 같은 모양이다.
*/
@DisplayName("수강신청 거부 규칙 R1~R8 (Requirements.md 4.1)")
class RegistrationValidatorTest {
private final RegistrationValidator validator = new RegistrationValidator(new ScheduleConflictChecker());
@Test
void registrationEndAtIsInclusive() {
Semester semester = TestFixtures.semester(18);
User user = TestFixtures.student("user", 1);
Lesson lesson = TestFixtures.lesson("lesson", TestFixtures.subject("subject", 3), semester, 30, null, null);
/** 이 도메인이 거부하는 방식. then이 도메인을 아는 지점은 여기 한 곳뿐이다. */
private static final Rejections<RegistrationException, RegistrationErrorCode> REJECTIONS =
Rejections.of(RegistrationException.class, RegistrationException::getErrorCode);
assertThatCode(() -> validator.validatePreconditions(user, lesson, semester.getRegistrationEndAt()))
.doesNotThrowAnyException();
@Nested
@DisplayName("R1 신청 기간 — 기간 밖이면 REGISTRATION_PERIOD_CLOSED")
class RegistrationPeriod {
@Test
@DisplayName("신청 종료 시각 정각에 신청하면 통과한다 (종료 시각은 기간에 포함된다)")
void endAtIsInclusive() {
RegistrationFixture fixture = RegistrationFixture.student(1);
Scenario.given(fixture)
.when(f -> f.checkEligibilityAt(fixture.registrationEndAt()))
.thenAccepted();
}
@Test
@DisplayName("기간이 지났으면 학년·역할 조건도 함께 어겨도 기간 오류를 먼저 반환한다")
void closedPeriodIsCheckedBeforeEligibility() {
Scenario.given(RegistrationFixture.student(1)
.inClosedSemester()
.requiringMinGrade(3)
.requiringRole(UserRole.POSTGRADUATE))
.when(RegistrationFixture::checkEligibility)
.thenRejectedWith(REJECTIONS, RegistrationErrorCode.REGISTRATION_PERIOD_CLOSED);
}
}
@Test
void rejectsClosedRegistrationPeriodBeforeEligibilityChecks() {
User user = TestFixtures.student("user", 1);
Lesson lesson = TestFixtures.lesson("lesson", TestFixtures.subject("subject", 3),
TestFixtures.closedSemester(), 30, 3L, UserRole.POSTGRADUATE);
assertError(RegistrationErrorCode.REGISTRATION_PERIOD_CLOSED,
() -> validator.validatePreconditions(user, lesson, TestFixtures.NOW));
@Nested
@DisplayName("R2 학년 제한 — 미달이면 NOT_ELIGIBLE_GRADE")
class MinGrade {
@Test
@DisplayName("1학년이 3학년 이상 강의를 신청하면 거부한다")
void rejectsGradeBelowMinimum() {
Scenario.given(RegistrationFixture.student(1)
.requiringMinGrade(3))
.when(RegistrationFixture::checkEligibility)
.thenRejectedWith(REJECTIONS, RegistrationErrorCode.NOT_ELIGIBLE_GRADE);
}
}
@Test
void rejectsGradeBelowMinimum() {
User user = TestFixtures.student("user", 1);
Lesson lesson = TestFixtures.lesson("lesson", TestFixtures.subject("subject", 3),
TestFixtures.semester(18), 30, 3L, null);
assertError(RegistrationErrorCode.NOT_ELIGIBLE_GRADE,
() -> validator.validatePreconditions(user, lesson, TestFixtures.NOW));
@Nested
@DisplayName("R3 역할 제한 — 불일치하면 NOT_ELIGIBLE_ROLE")
class AllowedRole {
@Test
@DisplayName("학부생이 대학원생 전용 강의를 신청하면 거부한다")
void rejectsRoleMismatch() {
Scenario.given(RegistrationFixture.student(3)
.requiringRole(UserRole.POSTGRADUATE))
.when(RegistrationFixture::checkEligibility)
.thenRejectedWith(REJECTIONS, RegistrationErrorCode.NOT_ELIGIBLE_ROLE);
}
}
@Test
void rejectsRoleMismatch() {
User user = TestFixtures.student("user", 3);
Lesson lesson = TestFixtures.lesson("lesson", TestFixtures.subject("subject", 3),
TestFixtures.semester(18), 30, null, UserRole.POSTGRADUATE);
@Nested
@DisplayName("R4·R5 중복 신청 — 같은 분반이면 ALREADY_REGISTERED, 다른 분반이면 DUPLICATE_SUBJECT")
class Duplicate {
@Test
@DisplayName("이미 신청한 그 강의를 다시 신청하면 과목 중복보다 강의 중복을 먼저 반환한다")
void sameLessonTakesPrecedenceOverSameSubject() {
Scenario.given(RegistrationFixture.student(2)
.alreadyRegisteredSameLesson())
.when(RegistrationFixture::register)
.thenRejectedWith(REJECTIONS, RegistrationErrorCode.ALREADY_REGISTERED);
}
assertError(RegistrationErrorCode.NOT_ELIGIBLE_ROLE,
() -> validator.validatePreconditions(user, lesson, TestFixtures.NOW));
@Test
@DisplayName("같은 과목의 다른 분반을 신청하면 거부한다")
void rejectsDifferentSectionOfSameSubject() {
Scenario.given(RegistrationFixture.student(2)
.applyingFor("subject", 3)
.alreadyRegistered("subject", 3))
.when(RegistrationFixture::register)
.thenRejectedWith(REJECTIONS, RegistrationErrorCode.DUPLICATE_SUBJECT);
}
}
@Test
void duplicateLessonTakesPrecedenceOverDuplicateSubject() {
Semester semester = TestFixtures.semester(18);
Subject subject = TestFixtures.subject("subject", 3);
User user = TestFixtures.student("user", 2);
Lesson lesson = TestFixtures.lesson("lesson", subject, semester, 30, null, null);
UserLesson existing = TestFixtures.registration("reg", user, lesson);
assertError(RegistrationErrorCode.ALREADY_REGISTERED,
() -> validator.validateLocked(lesson, List.of(existing), Map.of(), 1));
@Nested
@DisplayName("R6 시간표 충돌 — 겹치면 SCHEDULE_CONFLICT")
class ScheduleConflict {
@ParameterizedTest(name = "[{index}] {5}")
@CsvSource(textBlock = """
# 기존 수업 시작, 끝 | 신청 수업 시작, 끝 | 기대 에러(비우면 통과) | 설명
9, 11, 10, 12, SCHEDULE_CONFLICT, '기존 수업과 시간이 겹치면 거부한다 (월 9-11 vs 월 10-12)'
9, 11, 11, 13, , '앞 수업이 끝나는 시각에 시작하면 신청할 수 있다 (월 9-11 vs 월 11-13)'
""")
void scheduleOverlap(int existingStart, int existingEnd, int newStart, int newEnd,
RegistrationErrorCode expected, String description) {
Scenario.given(RegistrationFixture.student(2)
.alreadyRegistered("subject-a", 3)
.alreadyRegisteredOn(DayOfWeek.MONDAY, existingStart, existingEnd)
.applyingFor("subject-b", 3)
.scheduledOn(DayOfWeek.MONDAY, newStart, newEnd))
.when(RegistrationFixture::register)
.then(REJECTIONS, expected);
}
}
@Test
void rejectsDifferentSectionOfSameSubject() {
Semester semester = TestFixtures.semester(18);
Subject subject = TestFixtures.subject("subject", 3);
User user = TestFixtures.student("user", 2);
Lesson existingLesson = TestFixtures.lesson("lesson-a", subject, semester, 30, null, null);
Lesson newLesson = TestFixtures.lesson("lesson-b", subject, semester, 30, null, null);
UserLesson existing = TestFixtures.registration("reg", user, existingLesson);
@Nested
@DisplayName("R7 학점 상한 — 초과하면 CREDIT_LIMIT_EXCEEDED")
class CreditLimit {
@ParameterizedTest(name = "[{index}] {4}")
@CsvSource(textBlock = """
# 학기 상한 | 기존 신청 학점 | 신청 강의 학점 | 기대 에러(비우면 통과) | 설명
6, 3, 3, , '합계가 상한과 정확히 같으면 신청할 수 있다 (3+3=6)'
5, 3, 3, CREDIT_LIMIT_EXCEEDED , '합계가 상한을 넘으면 거부한다 (3+3>5)'
""")
void creditLimit(int maxCredits, int existingCredit, int newCredit,
RegistrationErrorCode expected, String description) {
RegistrationFixture fixture = RegistrationFixture.student(2)
.semesterWithMaxCredits(maxCredits)
.alreadyRegistered("subject-a", existingCredit)
.applyingFor("subject-b", newCredit);
assertError(RegistrationErrorCode.DUPLICATE_SUBJECT,
() -> validator.validateLocked(newLesson, List.of(existing), Map.of(), 1));
Scenario.given(fixture)
.when(RegistrationFixture::register)
.then(REJECTIONS, expected);
assertThat(fixture.totalCreditsAfter())
.as("신청 후 누적 학점")
.isEqualTo(existingCredit + newCredit);
}
}
@Test
void rejectsScheduleConflict() {
Semester semester = TestFixtures.semester(18);
User user = TestFixtures.student("user", 2);
Lesson existingLesson = TestFixtures.lesson("lesson-a", TestFixtures.subject("subject-a", 3), semester, 30, null, null);
Lesson newLesson = TestFixtures.lesson("lesson-b", TestFixtures.subject("subject-b", 3), semester, 30, null, null);
UserLesson existing = TestFixtures.registration("reg", user, existingLesson);
LessonSchedule existingSchedule = TestFixtures.schedule("schedule-a", existingLesson, DayOfWeek.MONDAY, 9, 11);
LessonSchedule newSchedule = TestFixtures.schedule("schedule-b", newLesson, DayOfWeek.MONDAY, 10, 12);
assertError(RegistrationErrorCode.SCHEDULE_CONFLICT,
() -> validator.validateLocked(newLesson, List.of(existing),
Map.of(existingLesson.getId(), List.of(existingSchedule), newLesson.getId(), List.of(newSchedule)), 1));
}
@Test
void scheduleBoundaryIsAllowed() {
Semester semester = TestFixtures.semester(18);
User user = TestFixtures.student("user", 2);
Lesson existingLesson = TestFixtures.lesson("lesson-a", TestFixtures.subject("subject-a", 3), semester, 30, null, null);
Lesson newLesson = TestFixtures.lesson("lesson-b", TestFixtures.subject("subject-b", 3), semester, 30, null, null);
UserLesson existing = TestFixtures.registration("reg", user, existingLesson);
LessonSchedule existingSchedule = TestFixtures.schedule("schedule-a", existingLesson, DayOfWeek.MONDAY, 9, 11);
LessonSchedule newSchedule = TestFixtures.schedule("schedule-b", newLesson, DayOfWeek.MONDAY, 11, 13);
assertThatCode(() -> validator.validateLocked(newLesson, List.of(existing),
Map.of(existingLesson.getId(), List.of(existingSchedule), newLesson.getId(), List.of(newSchedule)), 1))
.doesNotThrowAnyException();
}
@Test
void exactCreditLimitIsAllowed() {
Semester semester = TestFixtures.semester(6);
User user = TestFixtures.student("user", 2);
Lesson existingLesson = TestFixtures.lesson("lesson-a", TestFixtures.subject("subject-a", 3), semester, 30, null, null);
Lesson newLesson = TestFixtures.lesson("lesson-b", TestFixtures.subject("subject-b", 3), semester, 30, null, null);
UserLesson existing = TestFixtures.registration("reg", user, existingLesson);
assertThatCode(() -> validator.validateLocked(newLesson, List.of(existing), Map.of(), 1))
.doesNotThrowAnyException();
assertThat(validator.totalCreditsAfter(newLesson, List.of(existing))).isEqualTo(6);
}
@Test
void rejectsCreditAboveLimit() {
Semester semester = TestFixtures.semester(5);
User user = TestFixtures.student("user", 2);
Lesson existingLesson = TestFixtures.lesson("lesson-a", TestFixtures.subject("subject-a", 3), semester, 30, null, null);
Lesson newLesson = TestFixtures.lesson("lesson-b", TestFixtures.subject("subject-b", 3), semester, 30, null, null);
UserLesson existing = TestFixtures.registration("reg", user, existingLesson);
assertError(RegistrationErrorCode.CREDIT_LIMIT_EXCEEDED,
() -> validator.validateLocked(newLesson, List.of(existing), Map.of(), 1));
}
@Test
void lastCapacitySlotIsAllowedButFullClassIsRejected() {
Lesson lesson = TestFixtures.lesson("lesson", TestFixtures.subject("subject", 3),
TestFixtures.semester(18), 30, null, null);
assertThatCode(() -> validator.validateLocked(lesson, List.of(), Map.of(), 29))
.doesNotThrowAnyException();
assertError(RegistrationErrorCode.CAPACITY_EXCEEDED,
() -> validator.validateLocked(lesson, List.of(), Map.of(), 30));
}
private static void assertError(RegistrationErrorCode code, Runnable action) {
assertThatThrownBy(action::run)
.isInstanceOfSatisfying(RegistrationException.class,
ex -> assertThat(ex.getErrorCode()).isEqualTo(code));
@Nested
@DisplayName("R8 정원 — 가득 차면 CAPACITY_EXCEEDED")
class Capacity {
@ParameterizedTest(name = "[{index}] {3}")
@CsvSource(textBlock = """
# 정원 | 현재 유효 신청 수 | 기대 에러(비우면 통과) | 설명
30, 29, , '마지막 한 자리는 신청할 수 있다 (29/30)'
30, 30, CAPACITY_EXCEEDED , '정원이 가득 차면 거부한다 (30/30)'
""")
void capacity(int capacity, long enrolledCount,
RegistrationErrorCode expected, String description) {
Scenario.given(RegistrationFixture.student(2)
.withCapacity(capacity)
.alreadyEnrolled(enrolledCount))
.when(RegistrationFixture::register)
.then(REJECTIONS, expected);
}
}
}
@@ -3,44 +3,35 @@ package com.study.course_registration.service.policy;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.DayOfWeek;
import java.time.LocalTime;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import com.study.course_registration.entity.LessonSchedule;
@DisplayName("R6 시간 블록 겹침 판정 (Requirements.md 4.3)")
class ScheduleConflictCheckerTest {
private final ScheduleConflictChecker checker = new ScheduleConflictChecker();
@Test
void overlappingTimesOnSameDayConflict() {
LessonSchedule a = TestFixtures.schedule(DayOfWeek.MONDAY, 9, 11);
LessonSchedule b = TestFixtures.schedule(DayOfWeek.MONDAY, 10, 12);
@DisplayName("두 시간 블록이 겹치는지 판정한다")
@ParameterizedTest(name = "[{index}] {7}")
@CsvSource(textBlock = """
# 블록A 요일, 시작, 끝 | 블록B 요일, 시작, 끝 | 겹치는가 | 설명
MONDAY, 9, 11, MONDAY, 10, 12, true, '같은 요일에 시간이 겹치면 충돌이다'
MONDAY, 9, 11, MONDAY, 11, 13, false, '앞 수업이 끝나는 시각에 시작하면 충돌이 아니다'
MONDAY, 9, 11, MONDAY, 13, 15, false, '같은 요일이어도 시간이 떨어져 있으면 충돌이 아니다'
MONDAY, 9, 11, TUESDAY, 9, 11, false, '시간이 같아도 요일이 다르면 충돌이 아니다'
""")
void overlaps(DayOfWeek dayA, int startA, int endA,
DayOfWeek dayB, int startB, int endB,
boolean expected, String description) {
// given
LessonSchedule a = TestFixtures.schedule(dayA, startA, endA);
LessonSchedule b = TestFixtures.schedule(dayB, startB, endB);
assertThat(checker.overlaps(a, b)).isTrue();
}
@Test
void touchingBoundaryDoesNotConflict() {
LessonSchedule a = TestFixtures.schedule(DayOfWeek.MONDAY, 9, 11);
LessonSchedule b = TestFixtures.schedule(DayOfWeek.MONDAY, 11, 13);
assertThat(checker.overlaps(a, b)).isFalse();
}
@Test
void separatedTimesOnSameDayDoNotConflict() {
LessonSchedule a = TestFixtures.schedule(DayOfWeek.MONDAY, 9, 11);
LessonSchedule b = TestFixtures.schedule(DayOfWeek.MONDAY, 13, 15);
assertThat(checker.overlaps(a, b)).isFalse();
}
@Test
void sameTimeOnDifferentDayDoesNotConflict() {
LessonSchedule a = TestFixtures.schedule(DayOfWeek.MONDAY, 9, 11);
LessonSchedule b = TestFixtures.schedule(DayOfWeek.TUESDAY, 9, 11);
assertThat(checker.overlaps(a, b)).isFalse();
// when & then
assertThat(checker.overlaps(a, b)).as(description).isEqualTo(expected);
assertThat(checker.overlaps(b, a)).as(description + " (순서를 바꿔도 같다)").isEqualTo(expected);
}
}
@@ -0,0 +1,55 @@
package com.study.course_registration.support;
import static org.assertj.core.api.Assertions.assertThat;
/**
* then 단계. when의 실행 결과는 값을 돌려줬거나 예외로 거부됐거나 둘 중 하나다.
*
* <p>도메인 타입을 모른다. 예외 타입과 코드 추출 방식은 {@link Rejections}로 받는다.
*
* @param <R> when이 돌려준 값의 타입
*/
public final class Outcome<R> {
private final R result;
private final RuntimeException thrown;
Outcome(R result, RuntimeException thrown) {
this.result = result;
this.thrown = thrown;
}
/** then: 거부되지 않아야 한다. 돌려준 값을 그대로 넘겨주므로 이어서 내용을 확인할 수 있다. */
public R thenAccepted() {
if (thrown != null) {
throw new AssertionError("통과해야 하는데 " + thrown.getClass().getSimpleName()
+ " 이(가) 발생했다: " + thrown.getMessage(), thrown);
}
return result;
}
/**
* then: {@code expected}가 null이면 통과, 값이 있으면 그 코드로 거부되어야 한다.
*
* <p>표 기반 테스트에서 "기대 에러 칸이 비어 있으면 통과"를 그대로 표현하기 위한 형태다.
*/
public <X extends RuntimeException, E> void then(Rejections<X, E> rejections, E expected) {
if (expected == null) {
thenAccepted();
} else {
thenRejectedWith(rejections, expected);
}
}
/** then: 주어진 도메인의 예외로, 주어진 사유 코드로 거부되어야 한다. */
public <X extends RuntimeException, E> void thenRejectedWith(Rejections<X, E> rejections, E expected) {
assertThat(thrown)
.as("%s (으)로 거부되어야 하는데 통과했다", expected)
.isNotNull();
assertThat(thrown)
.as("거부 예외 타입")
.isInstanceOf(rejections.type());
assertThat(rejections.codeOf(thrown))
.as("거부 사유")
.isEqualTo(expected);
}
}
@@ -0,0 +1,39 @@
package com.study.course_registration.support;
import java.util.function.Function;
/**
* "이 도메인은 어떤 예외로 거부하고, 그 예외에서 사유 코드를 어떻게 꺼내는가"를 담은 값.
*
* <p>then 단계가 도메인에 묶이는 이유는 이 두 가지뿐이다. 그래서 이것만 값으로 넘기면
* then도 제네릭이 된다. 새 도메인은 상수 한 줄만 선언하면 된다.
*
* <pre>{@code
* Rejections.of(RegistrationException.class, RegistrationException::getErrorCode);
* Rejections.of(PaymentException.class, PaymentException::getCode);
* }</pre>
*
* @param <X> 그 도메인이 거부할 때 던지는 예외
* @param <E> 거부 사유 코드 타입 (보통 enum)
*/
public final class Rejections<X extends RuntimeException, E> {
private final Class<X> type;
private final Function<X, E> codeOf;
private Rejections(Class<X> type, Function<X, E> codeOf) {
this.type = type;
this.codeOf = codeOf;
}
public static <X extends RuntimeException, E> Rejections<X, E> of(Class<X> type, Function<X, E> codeOf) {
return new Rejections<>(type, codeOf);
}
Class<X> type() {
return type;
}
E codeOf(Throwable thrown) {
return codeOf.apply(type.cast(thrown));
}
}
@@ -0,0 +1,47 @@
package com.study.course_registration.support;
import java.util.function.Function;
/**
* given → when 을 표현하는 도메인 무관·계층 무관 테스트 하네스.
*
* <p>어떤 도메인 타입도, 어떤 계층(단위/통합/HTTP)도 여기 등장하지 않는다.
* "무언가를 준비해 두고(given) 무언가를 실행한다(when)"는 모양이 계층마다 같기 때문에
* 이 클래스는 도메인이나 계층이 늘어나도 수정할 일이 없다.
*
* <p>실행 중 튀어나온 {@link RuntimeException}은 여기서 잡아 {@link Outcome}에 담는다.
* then 단계에서 "통과해야 한다 / 이 코드로 거부되어야 한다"를 판정하기 위해서다.
*
* <pre>{@code
* Scenario.given(fixture).when(RegistrationFixture::register).thenRejectedWith(REJECTIONS, code);
* JsonBody body = Scenario.given(api).when(a -> a.post(path, json)).thenAccepted();
* }</pre>
*
* @param <T> 계층별 fixture 타입 (메모리 빌더, 서비스, HTTP 클라이언트 …)
*/
public final class Scenario<T> {
private final T fixture;
private Scenario(T fixture) {
this.fixture = fixture;
}
/** given: 준비된 fixture를 받는다. 어떻게 조립하는지는 각 도메인·계층이 안다. */
public static <T> Scenario<T> given(T fixture) {
return new Scenario<>(fixture);
}
/**
* when: fixture에 행동을 가하고 결과를 담아 돌려준다. 예외는 여기서 잡힌다.
*
* <p>값을 돌려주지 않는 행동은 fixture 자신을 반환하게 두면 된다. {@code when}이 하나뿐이라
* 계층이 달라져도 읽는 방식이 갈리지 않는다.
*/
public <R> Outcome<R> when(Function<T, R> action) {
try {
return new Outcome<>(action.apply(fixture), null);
} catch (RuntimeException thrown) {
return new Outcome<>(null, thrown);
}
}
}
@@ -0,0 +1,39 @@
package com.study.course_registration.support.http;
/**
* HTTP 응답이 4xx/5xx일 때 {@link JsonApi}가 던지는 예외.
*
* <p>HTTP는 예외를 던지지 않는다. 409는 던져진 게 아니라 <em>반환된 값</em>이다.
* 그대로 두면 단위·통합 계층과 표현법이 갈라지므로, 여기서 "거부 = 예외"로 번역해
* {@code Scenario.given(...).when(...).then(...)} 한 가지 흐름으로 읽히게 한다.
*
* <p>상태코드를 잃지 않도록 {@link #status()}를 그대로 들고 있는다. HTTP 계층에서만
* 볼 수 있는 값이 그것이기 때문이다.
*/
public final class ApiError extends RuntimeException {
private final int status;
private final String code;
private final String detail;
ApiError(int status, String code, String detail) {
super("HTTP " + status + " " + code + " — " + detail);
this.status = status;
this.code = code;
this.detail = detail;
}
/** 실제로 내려온 HTTP 상태코드 */
public int status() {
return status;
}
/** 응답 바디의 code 필드 (문자열 그대로. enum 변환은 도메인 쪽이 한다) */
public String code() {
return code;
}
/** 응답 바디의 message 필드 */
public String detail() {
return detail;
}
}
@@ -0,0 +1,76 @@
package com.study.course_registration.support.http;
import java.nio.charset.StandardCharsets;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import com.jayway.jsonpath.JsonPath;
/**
* MockMvc를 감싸 "2xx면 바디를 돌려주고, 4xx/5xx면 {@link ApiError}를 던지는" 클라이언트.
*
* <p>도메인을 모른다. 어떤 프로젝트의 어떤 엔드포인트에도 그대로 쓸 수 있고,
* 에러 바디가 {@code code}/{@code message} 필드를 갖는다는 것만 전제한다.
*
* <p>MockMvc를 여기서만 부르므로, 안쪽 API를 나중에 바꿔도 테스트는 그대로다.
*/
public final class JsonApi {
private final MockMvc mockMvc;
public JsonApi(MockMvc mockMvc) {
this.mockMvc = mockMvc;
}
public JsonBody post(String path, String jsonBody) {
return exchange(MockMvcRequestBuilders.post(path)
.contentType(MediaType.APPLICATION_JSON)
.content(jsonBody));
}
public JsonBody get(String path) {
return exchange(MockMvcRequestBuilders.get(path));
}
public JsonBody delete(String path) {
return exchange(MockMvcRequestBuilders.delete(path));
}
private JsonBody exchange(MockHttpServletRequestBuilder request) {
MockHttpServletResponse response;
try {
response = mockMvc.perform(request).andReturn().getResponse();
} catch (Exception e) {
throw new IllegalStateException("요청을 보내지 못했다: " + request, e);
}
String body = readBody(response);
if (response.getStatus() >= 400) {
throw new ApiError(response.getStatus(), readField(body, "$.code"), readField(body, "$.message"));
}
return new JsonBody(response.getStatus(), body);
}
private static String readBody(MockHttpServletResponse response) {
try {
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
return response.getContentAsString(StandardCharsets.UTF_8);
} catch (Exception e) {
throw new IllegalStateException("응답 본문을 읽지 못했다", e);
}
}
private static String readField(String body, String path) {
if (body == null || body.isBlank()) {
return "(빈 응답 본문)";
}
try {
return String.valueOf(JsonPath.<Object>read(body, path));
} catch (RuntimeException e) {
return "(" + path + " 없음: " + body + ")";
}
}
}
@@ -0,0 +1,48 @@
package com.study.course_registration.support.http;
import java.util.Set;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
/**
* 2xx 응답. 상태코드와 본문을 함께 들고 있다.
*
* <p>상태코드를 여기 싣는 이유: {@code thenAccepted()}는 "거부되지 않았다"까지만 판정한다.
* 201과 200을 구분하는 건 그 다음 질문이고, 그 질문에 답할 값이 없으면
* "201을 돌려준다"고 이름 붙인 테스트가 200에서도 통과한다.
*/
public final class JsonBody {
private final int status;
private final String raw;
JsonBody(int status, String raw) {
this.status = status;
this.raw = raw;
}
/** 실제로 내려온 HTTP 상태코드 */
public int status() {
return status;
}
/** 예: {@code body.at("$.totalCredits")} */
public <T> T at(String jsonPath) {
return JsonPath.read(raw, jsonPath);
}
/**
* 최상위 필드 이름 전부. 응답 스키마를 통째로 고정할 때 쓴다.
*
* <p>값이 아니라 <em>이름</em>을 보는 이유: 필드 이름은 클라이언트와의 계약이다.
* 값 몇 개만 확인하면 이름이 바뀌어도 테스트가 통과한다.
*/
public Set<String> fieldNames() {
DocumentContext ctx = JsonPath.parse(raw);
return ctx.read("$.keys()", Set.class);
}
public String raw() {
return raw;
}
}