feat : 수강신청 도메인 구성

This commit is contained in:
donghyeon-ka
2026-09-18 15:20:54 +09:00
parent 3e33388e02
commit 70d71008c6
61 changed files with 2835 additions and 258 deletions
@@ -0,0 +1,202 @@
package com.study.course_registration.service;
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 java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import com.study.course_registration.dto.registration.CourseRegistrationRequest;
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.exception.RegistrationException;
import com.study.course_registration.repository.*;
@SpringBootTest
@ActiveProfiles("test")
class CourseRegistrationConcurrencyIntegrationTest {
@Autowired CourseRegistrationService service;
@Autowired UserLessonRepository userLessonRepository;
@Autowired LessonScheduleRepository lessonScheduleRepository;
@Autowired LessonRepository lessonRepository;
@Autowired SubjectRepository subjectRepository;
@Autowired ProfessorRepository professorRepository;
@Autowired SemesterRepository semesterRepository;
@Autowired UserRepository userRepository;
private ExecutorService executor;
private Semester semester;
private Professor professor;
@BeforeEach
void setUp() {
clearData();
Instant now = Instant.now();
semester = semesterRepository.save(new Semester("semester", "2026-1", LocalDate.now().minusDays(1),
LocalDate.now().plusDays(100), now.minusSeconds(3600), now.plusSeconds(3600), 18));
professor = professorRepository.save(new Professor("professor", "교수"));
}
@AfterEach
void tearDown() throws InterruptedException {
if (executor != null) {
executor.shutdownNow();
executor.awaitTermination(5, TimeUnit.SECONDS);
}
}
@Test
void capacityOneWithTenConcurrentUsersHasExactlyOneSuccess() throws Exception {
Lesson lesson = lesson("lesson-cap1", "subject-cap1", 3, 1, DayOfWeek.MONDAY, 9, 11);
List<User> users = users(10, "cap1-user-");
List<RegistrationErrorCode> results = runConcurrent(users.stream()
.<ThrowingAction>map(user -> () -> service.register(user.getId(), new CourseRegistrationRequest(lesson.getId())))
.toList());
assertThat(results.stream().filter(code -> code == null)).hasSize(1);
assertThat(results.stream().filter(code -> code == RegistrationErrorCode.CAPACITY_EXCEEDED)).hasSize(9);
assertThat(userLessonRepository.countByLesson_IdAndCanceledAtIsNull(lesson.getId())).isEqualTo(1);
}
@Test
void sameStudentConcurrentLessonsCannotExceedCreditLimit() throws Exception {
replaceSemesterWithMaxCredits(3);
User user = userRepository.save(new User("credit-user", "학생", 2L, UserRole.STUDENT));
Lesson lessonA = lesson("credit-a", "credit-subject-a", 3, 30, DayOfWeek.MONDAY, 9, 11);
Lesson lessonB = lesson("credit-b", "credit-subject-b", 3, 30, DayOfWeek.TUESDAY, 9, 11);
List<RegistrationErrorCode> results = runConcurrent(List.of(
() -> service.register(user.getId(), new CourseRegistrationRequest(lessonA.getId())),
() -> service.register(user.getId(), new CourseRegistrationRequest(lessonB.getId()))));
assertThat(results.stream().filter(code -> code == null)).hasSize(1);
assertThat(results.stream().filter(code -> code == RegistrationErrorCode.CREDIT_LIMIT_EXCEEDED)).hasSize(1);
}
@Test
void sameStudentConcurrentOverlappingLessonsRejectOneConflict() throws Exception {
User user = userRepository.save(new User("schedule-user", "학생", 2L, UserRole.STUDENT));
Lesson lessonA = lesson("schedule-a", "schedule-subject-a", 3, 30, DayOfWeek.MONDAY, 9, 11);
Lesson lessonB = lesson("schedule-b", "schedule-subject-b", 3, 30, DayOfWeek.MONDAY, 10, 12);
List<RegistrationErrorCode> results = runConcurrent(List.of(
() -> service.register(user.getId(), new CourseRegistrationRequest(lessonA.getId())),
() -> service.register(user.getId(), new CourseRegistrationRequest(lessonB.getId()))));
assertThat(results.stream().filter(code -> code == null)).hasSize(1);
assertThat(results.stream().filter(code -> code == RegistrationErrorCode.SCHEDULE_CONFLICT)).hasSize(1);
}
@Test
void sameStudentSameLessonConcurrentRequestsRejectDuplicate() throws Exception {
User user = userRepository.save(new User("duplicate-user", "학생", 2L, UserRole.STUDENT));
Lesson lesson = lesson("duplicate-lesson", "duplicate-subject", 3, 30, DayOfWeek.WEDNESDAY, 9, 11);
List<RegistrationErrorCode> results = runConcurrent(List.of(
() -> service.register(user.getId(), new CourseRegistrationRequest(lesson.getId())),
() -> service.register(user.getId(), new CourseRegistrationRequest(lesson.getId()))));
assertThat(results.stream().filter(code -> code == null)).hasSize(1);
assertThat(results.stream().filter(code -> code == RegistrationErrorCode.ALREADY_REGISTERED)).hasSize(1);
}
@Test
void capacityThirtyWithFiftyConcurrentUsersStopsAtThirty() throws Exception {
Lesson lesson = lesson("lesson-cap30", "subject-cap30", 3, 30, DayOfWeek.THURSDAY, 9, 11);
List<User> users = users(50, "cap30-user-");
List<RegistrationErrorCode> results = runConcurrent(users.stream()
.<ThrowingAction>map(user -> () -> service.register(user.getId(), new CourseRegistrationRequest(lesson.getId())))
.toList());
assertThat(results.stream().filter(code -> code == null)).hasSize(30);
assertThat(results.stream().filter(code -> code == RegistrationErrorCode.CAPACITY_EXCEEDED)).hasSize(20);
assertThat(userLessonRepository.countByLesson_IdAndCanceledAtIsNull(lesson.getId())).isEqualTo(30);
}
private void replaceSemesterWithMaxCredits(int maxCredits) {
userLessonRepository.deleteAll();
lessonScheduleRepository.deleteAll();
lessonRepository.deleteAll();
semesterRepository.deleteAll();
Instant now = Instant.now();
semester = semesterRepository.save(new Semester("semester", "2026-1", LocalDate.now().minusDays(1),
LocalDate.now().plusDays(100), now.minusSeconds(3600), now.plusSeconds(3600), maxCredits));
}
private void clearData() {
userLessonRepository.deleteAll();
lessonScheduleRepository.deleteAll();
lessonRepository.deleteAll();
subjectRepository.deleteAll();
professorRepository.deleteAll();
semesterRepository.deleteAll();
userRepository.deleteAll();
}
private Lesson lesson(String lessonId, String subjectId, int credit, int capacity,
DayOfWeek day, int startHour, int endHour) {
Subject subject = subjectRepository.save(new Subject(subjectId, subjectId, subjectId, subjectId, credit));
Lesson lesson = lessonRepository.save(new Lesson(lessonId, lessonId, subject, professor, semester, capacity, null, null));
lessonScheduleRepository.save(new LessonSchedule("schedule-" + lessonId, lesson, day,
LocalTime.of(startHour, 0), LocalTime.of(endHour, 0)));
return lesson;
}
private List<User> users(int count, String prefix) {
List<User> users = new ArrayList<>();
for (int index = 0; index < count; index++) {
users.add(new User(prefix + index, "학생" + index, 2L, UserRole.STUDENT));
}
return userRepository.saveAll(users);
}
private List<RegistrationErrorCode> runConcurrent(List<ThrowingAction> actions) throws Exception {
executor = Executors.newFixedThreadPool(actions.size());
CountDownLatch ready = new CountDownLatch(actions.size());
CountDownLatch start = new CountDownLatch(1);
CountDownLatch done = new CountDownLatch(actions.size());
List<RegistrationErrorCode> results = Collections.synchronizedList(new ArrayList<>());
List<Throwable> unexpected = Collections.synchronizedList(new ArrayList<>());
for (ThrowingAction action : actions) {
executor.submit(() -> {
ready.countDown();
try {
start.await();
action.run();
results.add(null);
} catch (RegistrationException exception) {
results.add(exception.getErrorCode());
} catch (Throwable throwable) {
unexpected.add(throwable);
} finally {
done.countDown();
}
});
}
assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue();
start.countDown();
assertThat(done.await(30, TimeUnit.SECONDS)).isTrue();
assertThat(unexpected).isEmpty();
return results;
}
@FunctionalInterface
private interface ThrowingAction {
void run() throws Exception;
}
}
@@ -0,0 +1,171 @@
package com.study.course_registration.service;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
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.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import com.study.course_registration.dto.registration.CourseRegistrationRequest;
import com.study.course_registration.dto.registration.CourseRegistrationResponse;
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.exception.RegistrationException;
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;
@SpringBootTest
@ActiveProfiles("test")
class CourseRegistrationServiceIntegrationTest {
@Autowired CourseRegistrationService service;
@Autowired UserLessonRepository userLessonRepository;
@Autowired LessonScheduleRepository lessonScheduleRepository;
@Autowired LessonRepository lessonRepository;
@Autowired SubjectRepository subjectRepository;
@Autowired ProfessorRepository professorRepository;
@Autowired SemesterRepository semesterRepository;
@Autowired UserRepository userRepository;
private Semester semester;
private User user;
private Subject subjectA;
private Subject subjectB;
private Professor professor;
private Lesson lessonA;
private Lesson lessonB;
@BeforeEach
void setUp() {
userLessonRepository.deleteAll();
lessonScheduleRepository.deleteAll();
lessonRepository.deleteAll();
subjectRepository.deleteAll();
professorRepository.deleteAll();
semesterRepository.deleteAll();
userRepository.deleteAll();
Instant now = Instant.now();
semester = semesterRepository.save(new Semester("semester", "2026-1", LocalDate.now().minusDays(1),
LocalDate.now().plusDays(100), now.minusSeconds(3600), now.plusSeconds(3600), 18));
professor = professorRepository.save(new Professor("professor", "교수"));
subjectA = subjectRepository.save(new Subject("subject-a", "과목A", "A101", "A", 3));
subjectB = subjectRepository.save(new Subject("subject-b", "과목B", "B101", "B", 3));
user = userRepository.save(new User("user", "학생", 2L, UserRole.STUDENT));
lessonA = lessonRepository.save(new Lesson("lesson-a", "강의A", subjectA, professor, semester, 30, null, null));
lessonB = lessonRepository.save(new Lesson("lesson-b", "강의B", subjectB, professor, semester, 30, null, null));
lessonScheduleRepository.save(new LessonSchedule("schedule-a", lessonA, DayOfWeek.MONDAY, LocalTime.of(9, 0), LocalTime.of(11, 0)));
lessonScheduleRepository.save(new LessonSchedule("schedule-b", lessonB, DayOfWeek.TUESDAY, LocalTime.of(9, 0), LocalTime.of(11, 0)));
}
@Test
void registerCreatesActiveRegistrationAndReturnsTotalCredits() {
CourseRegistrationResponse response = service.register(user.getId(), new CourseRegistrationRequest(lessonA.getId()));
assertThat(response.userId()).isEqualTo(user.getId());
assertThat(response.lessonId()).isEqualTo(lessonA.getId());
assertThat(response.totalCredits()).isEqualTo(3);
assertThat(userLessonRepository.countByLesson_IdAndCanceledAtIsNull(lessonA.getId())).isEqualTo(1);
}
@Test
void duplicateRegistrationIsRejected() {
service.register(user.getId(), new CourseRegistrationRequest(lessonA.getId()));
assertThatThrownBy(() -> service.register(user.getId(), new CourseRegistrationRequest(lessonA.getId())))
.isInstanceOfSatisfying(RegistrationException.class,
ex -> assertThat(ex.getErrorCode()).isEqualTo(RegistrationErrorCode.ALREADY_REGISTERED));
}
@Test
void cancelThenReregisterKeepsHistoryAndOneActiveRow() {
CourseRegistrationResponse first = service.register(user.getId(), new CourseRegistrationRequest(lessonA.getId()));
service.cancel(user.getId(), first.registrationId());
CourseRegistrationResponse second = service.register(user.getId(), new CourseRegistrationRequest(lessonA.getId()));
assertThat(second.registrationId()).isNotEqualTo(first.registrationId());
assertThat(userLessonRepository.findAll()).hasSize(2);
assertThat(userLessonRepository.findAll().stream().filter(it -> it.getCanceledAt() == null)).hasSize(1);
}
@Test
void otherUserCannotCancelRegistration() {
CourseRegistrationResponse first = service.register(user.getId(), new CourseRegistrationRequest(lessonA.getId()));
User other = userRepository.save(new User("other-user", "다른학생", 2L, UserRole.STUDENT));
assertThatThrownBy(() -> service.cancel(other.getId(), first.registrationId()))
.isInstanceOfSatisfying(RegistrationException.class,
ex -> assertThat(ex.getErrorCode()).isEqualTo(RegistrationErrorCode.REGISTRATION_FORBIDDEN));
}
@Test
void cancelingAlreadyCanceledRegistrationIsRejected() {
CourseRegistrationResponse first = service.register(user.getId(), new CourseRegistrationRequest(lessonA.getId()));
service.cancel(user.getId(), first.registrationId());
assertThatThrownBy(() -> service.cancel(user.getId(), first.registrationId()))
.isInstanceOfSatisfying(RegistrationException.class,
ex -> assertThat(ex.getErrorCode()).isEqualTo(RegistrationErrorCode.ALREADY_CANCELED));
}
@Test
void cancelingFreesCapacityForNextRegistration() {
Lesson capacityOne = lessonRepository.save(new Lesson("capacity-one", "정원1", subjectB, professor, semester, 1, null, null));
lessonScheduleRepository.save(new LessonSchedule("capacity-one-schedule", capacityOne, DayOfWeek.WEDNESDAY, LocalTime.of(13, 0), LocalTime.of(15, 0)));
User other = userRepository.save(new User("capacity-other", "다른학생", 2L, UserRole.STUDENT));
CourseRegistrationResponse first = service.register(user.getId(), new CourseRegistrationRequest(capacityOne.getId()));
service.cancel(user.getId(), first.registrationId());
CourseRegistrationResponse second = service.register(other.getId(), new CourseRegistrationRequest(capacityOne.getId()));
assertThat(second.userId()).isEqualTo(other.getId());
assertThat(userLessonRepository.countByLesson_IdAndCanceledAtIsNull(capacityOne.getId())).isEqualTo(1);
}
@Test
void cancellationOutsideRegistrationPeriodIsRejected() {
CourseRegistrationResponse registration = service.register(user.getId(), new CourseRegistrationRequest(lessonA.getId()));
Semester closedSemester = semesterRepository.save(new Semester("closed-semester", "closed", LocalDate.now().minusDays(100),
LocalDate.now().plusDays(100), Instant.now().minusSeconds(7200), Instant.now().minusSeconds(3600), 18));
Lesson closedLesson = lessonRepository.save(new Lesson("closed-lesson", "마감강의", subjectB, professor, closedSemester, 30, null, null));
lessonScheduleRepository.save(new LessonSchedule("closed-schedule", closedLesson, DayOfWeek.THURSDAY, LocalTime.of(9, 0), LocalTime.of(11, 0)));
var closedRegistration = userLessonRepository.saveAndFlush(new com.study.course_registration.entity.UserLesson(user, closedLesson));
assertThatThrownBy(() -> service.cancel(user.getId(), closedRegistration.getId()))
.isInstanceOfSatisfying(RegistrationException.class,
ex -> assertThat(ex.getErrorCode()).isEqualTo(RegistrationErrorCode.REGISTRATION_PERIOD_CLOSED));
assertThat(userLessonRepository.findById(registration.registrationId())).isPresent();
}
@Test
void activeRegistrationListOmitsCanceledRows() {
CourseRegistrationResponse first = service.register(user.getId(), new CourseRegistrationRequest(lessonA.getId()));
service.cancel(user.getId(), first.registrationId());
service.register(user.getId(), new CourseRegistrationRequest(lessonB.getId()));
var response = service.getRegistrations(user.getId(), semester.getId());
assertThat(response.totalCredits()).isEqualTo(3);
assertThat(response.registrations()).extracting(it -> it.lessonId()).containsExactly(lessonB.getId());
}
}
@@ -0,0 +1,96 @@
package com.study.course_registration.service;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
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.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import com.study.course_registration.dto.registration.CourseRegistrationRequest;
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.exception.RegistrationException;
import com.study.course_registration.repository.*;
@SpringBootTest
@ActiveProfiles("test")
class LessonQueryServiceIntegrationTest {
@Autowired LessonQueryService lessonQueryService;
@Autowired CourseRegistrationService registrationService;
@Autowired UserLessonRepository userLessonRepository;
@Autowired LessonScheduleRepository lessonScheduleRepository;
@Autowired LessonRepository lessonRepository;
@Autowired SubjectRepository subjectRepository;
@Autowired ProfessorRepository professorRepository;
@Autowired SemesterRepository semesterRepository;
@Autowired UserRepository userRepository;
private Semester semester;
private Lesson lesson;
private User user;
@BeforeEach
void setUp() {
userLessonRepository.deleteAll();
lessonScheduleRepository.deleteAll();
lessonRepository.deleteAll();
subjectRepository.deleteAll();
professorRepository.deleteAll();
semesterRepository.deleteAll();
userRepository.deleteAll();
Instant now = Instant.now();
semester = semesterRepository.save(new Semester("semester-query", "2026-1", LocalDate.now().minusDays(1),
LocalDate.now().plusDays(100), now.minusSeconds(3600), now.plusSeconds(3600), 18));
Professor professor = professorRepository.save(new Professor("prof-query", "조회교수"));
Subject subject = subjectRepository.save(new Subject("subject-query", "자료구조", "CS202", "자료구조 설명", 3));
lesson = lessonRepository.save(new Lesson("lesson-query", "자료구조 01", subject, professor, semester, 30, null, null));
lessonScheduleRepository.save(new LessonSchedule("schedule-query", lesson, DayOfWeek.MONDAY,
LocalTime.of(9, 0), LocalTime.of(11, 0)));
user = userRepository.save(new User("user-query", "조회학생", 2L, UserRole.STUDENT));
registrationService.register(user.getId(), new CourseRegistrationRequest(lesson.getId()));
}
@Test
void listUsesCurrentSemesterAndReturnsBulkDerivedFields() {
var response = lessonQueryService.getLessons(null, null, 0, 20);
assertThat(response.totalElements()).isEqualTo(1);
assertThat(response.lessons()).singleElement().satisfies(item -> {
assertThat(item.lessonId()).isEqualTo(lesson.getId());
assertThat(item.enrolledCount()).isEqualTo(1);
assertThat(item.schedules()).hasSize(1);
});
}
@Test
void detailContainsSubjectAndSemesterRegistrationMetadata() {
var response = lessonQueryService.getLesson(lesson.getId());
assertThat(response.subjectDescription()).isEqualTo("자료구조 설명");
assertThat(response.semesterName()).isEqualTo(semester.getName());
assertThat(response.enrolledCount()).isEqualTo(1);
assertThat(response.registrationStartAt().toEpochMilli()).isEqualTo(semester.getRegistrationStartAt().toEpochMilli());
}
@Test
void unknownSemesterIsRejected() {
assertThatThrownBy(() -> lessonQueryService.getLessons("missing", null, 0, 20))
.isInstanceOfSatisfying(RegistrationException.class,
ex -> assertThat(ex.getErrorCode()).isEqualTo(RegistrationErrorCode.SEMESTER_NOT_FOUND));
}
}
@@ -0,0 +1,163 @@
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.Test;
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;
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);
assertThatCode(() -> validator.validatePreconditions(user, lesson, semester.getRegistrationEndAt()))
.doesNotThrowAnyException();
}
@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));
}
@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));
}
@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);
assertError(RegistrationErrorCode.NOT_ELIGIBLE_ROLE,
() -> validator.validatePreconditions(user, lesson, TestFixtures.NOW));
}
@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));
}
@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);
assertError(RegistrationErrorCode.DUPLICATE_SUBJECT,
() -> validator.validateLocked(newLesson, List.of(existing), Map.of(), 1));
}
@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));
}
}
@@ -0,0 +1,46 @@
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 com.study.course_registration.entity.LessonSchedule;
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);
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();
}
}
@@ -0,0 +1,63 @@
package com.study.course_registration.service.policy;
import java.time.DayOfWeek;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalTime;
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.entity.UserLesson;
import com.study.course_registration.enums.UserRole;
final class TestFixtures {
static final Instant NOW = Instant.parse("2026-09-17T10:00:00Z");
private TestFixtures() {
}
static Semester semester(int maxCredits) {
return new Semester("semester-1", "2026-1", LocalDate.of(2026, 9, 1), LocalDate.of(2026, 12, 31),
NOW.minusSeconds(3600), NOW.plusSeconds(3600), maxCredits);
}
static Semester closedSemester() {
return new Semester("semester-closed", "closed", LocalDate.of(2026, 1, 1), LocalDate.of(2026, 2, 1),
NOW.minusSeconds(7200), NOW.minusSeconds(3600), 18);
}
static User student(String id, long grade) {
return new User(id, id, grade, UserRole.STUDENT);
}
static User postgraduate(String id) {
return new User(id, id, 3L, UserRole.POSTGRADUATE);
}
static Lesson lesson(String id, Subject subject, Semester semester, int capacity, Long minGrade, UserRole role) {
return new Lesson(id, id, subject, new Professor("prof-" + id, "prof"), semester, capacity, minGrade, role);
}
static Subject subject(String id, int credit) {
return new Subject(id, id, id, id, credit);
}
static UserLesson registration(String id, User user, Lesson lesson) {
return new UserLesson(id, user, lesson);
}
static LessonSchedule schedule(DayOfWeek day, int startHour, int endHour) {
Subject subject = subject("subject-" + day + startHour, 3);
Lesson lesson = lesson("lesson-" + day + startHour, subject, semester(18), 30, null, null);
return new LessonSchedule("schedule-" + day + startHour, lesson, day,
LocalTime.of(startHour, 0), LocalTime.of(endHour, 0));
}
static LessonSchedule schedule(String id, Lesson lesson, DayOfWeek day, int startHour, int endHour) {
return new LessonSchedule(id, lesson, day, LocalTime.of(startHour, 0), LocalTime.of(endHour, 0));
}
}
+21
View File
@@ -0,0 +1,21 @@
spring:
datasource:
url: jdbc:h2:mem:course_test;DB_CLOSE_DELAY=-1;MODE=PostgreSQL;LOCK_TIMEOUT=3000
driver-class-name: org.h2.Driver
username: sa
password:
jpa:
hibernate:
ddl-auto: create-drop
open-in-view: false
h2:
console:
enabled: false
app:
seed:
enabled: false
springdoc:
api-docs:
enabled: false
swagger-ui:
enabled: false