refactor: 테스트 GWT로 통일해서 사용할 수 있도록 구성 및 서브에이전트 파일 수정
This commit is contained in:
@@ -2,8 +2,10 @@ package com.study.course_registration;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
|
||||
@SpringBootTest
|
||||
@ActiveProfiles("test")
|
||||
class CourseRegistrationApplicationTests {
|
||||
|
||||
@Test
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
package com.study.course_registration.architecture;
|
||||
|
||||
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes;
|
||||
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses;
|
||||
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noFields;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.tngtech.archunit.core.domain.JavaClasses;
|
||||
import com.tngtech.archunit.core.importer.ClassFileImporter;
|
||||
|
||||
import java.nio.file.Path;
|
||||
|
||||
import jakarta.persistence.ManyToMany;
|
||||
import jakarta.persistence.OneToMany;
|
||||
import jakarta.persistence.OneToOne;
|
||||
|
||||
class ArchitectureTest {
|
||||
@Test
|
||||
@DisplayName("수강신청 mutation → RegistrationLockManager 의존")
|
||||
void registrationMutationUsesLockBoundary() {
|
||||
JavaClasses classes = new ClassFileImporter().importPath(Path.of("build/classes/java/main"));
|
||||
|
||||
classes()
|
||||
.that().haveSimpleName("CourseRegistrationService")
|
||||
.should().dependOnClassesThat().haveSimpleName("RegistrationLockManager")
|
||||
.check(classes);
|
||||
|
||||
noClasses()
|
||||
.that().haveSimpleName("CourseRegistrationService")
|
||||
.should().dependOnClassesThat().haveSimpleName("LessonRepository")
|
||||
.check(classes);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("새 service → registration write repository 우회 금지")
|
||||
void registrationWriteRepositoriesStayInsideApprovedServices() {
|
||||
JavaClasses classes = new ClassFileImporter().importPath(Path.of("build/classes/java/main"));
|
||||
|
||||
noClasses()
|
||||
.that().resideInAPackage("..service..")
|
||||
.and().doNotHaveSimpleName("CourseRegistrationService")
|
||||
.and().doNotHaveSimpleName("LessonQueryService")
|
||||
.should().dependOnClassesThat().haveSimpleName("UserLessonRepository")
|
||||
.check(classes);
|
||||
|
||||
noClasses()
|
||||
.that().resideInAPackage("..service..")
|
||||
.and().doNotHaveSimpleName("CourseRegistrationService")
|
||||
.should().dependOnClassesThat().haveSimpleName("RegistrationIdempotencyRepository")
|
||||
.check(classes);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("엔티티 연관관계 → ManyToOne만 허용")
|
||||
void entityAssociationsUseManyToOneOnly() {
|
||||
JavaClasses classes = new ClassFileImporter().importPath(Path.of("build/classes/java/main"));
|
||||
|
||||
noFields()
|
||||
.that().areDeclaredInClassesThat().resideInAPackage("..entity..")
|
||||
.should().beAnnotatedWith(OneToOne.class)
|
||||
.check(classes);
|
||||
noFields()
|
||||
.that().areDeclaredInClassesThat().resideInAPackage("..entity..")
|
||||
.should().beAnnotatedWith(OneToMany.class)
|
||||
.check(classes);
|
||||
noFields()
|
||||
.that().areDeclaredInClassesThat().resideInAPackage("..entity..")
|
||||
.should().beAnnotatedWith(ManyToMany.class)
|
||||
.check(classes);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.study.course_registration.architecture;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class SourceStyleTest {
|
||||
private static final Pattern LOCAL_VAR = Pattern.compile("\\bvar\\s+[A-Za-z_$][A-Za-z0-9_$]*");
|
||||
private static final Pattern FQCN = Pattern.compile(
|
||||
"(?:com\\.study\\.course_registration(?:\\.[a-z_][a-z0-9_]*)+|java\\.(?:util|time)(?:\\.[a-z_][a-z0-9_]*)*)\\.[A-Z][A-Za-z0-9_$]*");
|
||||
|
||||
@Test
|
||||
@DisplayName("소스 스타일 → var·본문 FQCN·wildcard import 금지")
|
||||
void sourceStyle() throws IOException {
|
||||
List<String> violations = new ArrayList<>();
|
||||
|
||||
for (Path sourceRoot : List.of(Path.of("src/main/java"), Path.of("src/test/java"))) {
|
||||
try (Stream<Path> files = Files.walk(sourceRoot)) {
|
||||
files.filter(path -> path.toString().endsWith(".java"))
|
||||
.forEach(path -> inspect(path, violations));
|
||||
}
|
||||
}
|
||||
|
||||
assertThat(violations)
|
||||
.as("명시적 타입/import 규칙 위반")
|
||||
.isEmpty();
|
||||
}
|
||||
|
||||
private static void inspect(Path path, List<String> violations) {
|
||||
try {
|
||||
List<String> lines = Files.readAllLines(path);
|
||||
for (int index = 0; index < lines.size(); index++) {
|
||||
String line = lines.get(index);
|
||||
String trimmed = line.trim();
|
||||
|
||||
if (trimmed.startsWith("import ") && trimmed.contains(".*;")) {
|
||||
violations.add(location(path, index, "wildcard import"));
|
||||
}
|
||||
if (LOCAL_VAR.matcher(line).find()) {
|
||||
violations.add(location(path, index, "var"));
|
||||
}
|
||||
if (!trimmed.startsWith("package ")
|
||||
&& !trimmed.startsWith("import ")
|
||||
&& FQCN.matcher(line).find()) {
|
||||
violations.add(location(path, index, "본문 FQCN"));
|
||||
}
|
||||
}
|
||||
} catch (IOException exception) {
|
||||
throw new IllegalStateException("소스 스타일 검사 실패: " + path, exception);
|
||||
}
|
||||
}
|
||||
|
||||
private static String location(Path path, int zeroBasedLine, String reason) {
|
||||
return path + ":" + (zeroBasedLine + 1) + " " + reason;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.study.course_registration.config;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.study.course_registration.enums.UserRole;
|
||||
|
||||
class EnumConverterTest {
|
||||
@Test
|
||||
@DisplayName("DayOfWeek → ISO 요일 번호")
|
||||
void dayOfWeek() {
|
||||
DayOfWeekConverter converter = new DayOfWeekConverter();
|
||||
|
||||
assertThat(converter.convertToDatabaseColumn(DayOfWeek.MONDAY)).isEqualTo(1);
|
||||
assertThat(converter.convertToEntityAttribute(7)).isEqualTo(DayOfWeek.SUNDAY);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("UserRole → 이름 문자열")
|
||||
void userRole() {
|
||||
UserRoleConverter converter = new UserRoleConverter();
|
||||
|
||||
assertThat(converter.convertToDatabaseColumn(UserRole.POSTGRADUATE)).isEqualTo("POSTGRADUATE");
|
||||
assertThat(converter.convertToEntityAttribute("STUDENT")).isEqualTo(UserRole.STUDENT);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
@DisplayName("enum null → DB null")
|
||||
void nullValues() {
|
||||
DayOfWeekConverter day = new DayOfWeekConverter();
|
||||
UserRoleConverter role = new UserRoleConverter();
|
||||
|
||||
assertThat(day.convertToDatabaseColumn(null)).isNull();
|
||||
assertThat(day.convertToEntityAttribute(null)).isNull();
|
||||
assertThat(role.convertToDatabaseColumn(null)).isNull();
|
||||
assertThat(role.convertToEntityAttribute(null)).isNull();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.study.course_registration.config;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThatCode;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class RuntimeProfileConfigTest {
|
||||
@Test
|
||||
@DisplayName("환경 profile 없음 → 기동 거부")
|
||||
void missingProfile() {
|
||||
assertThatThrownBy(() -> RuntimeProfileConfig.requireValidProfiles(new String[0]))
|
||||
.isInstanceOf(IllegalStateException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("오타 profile만 활성화 → 기동 거부")
|
||||
void typoProfile() {
|
||||
assertThatThrownBy(() -> RuntimeProfileConfig.requireValidProfiles(new String[]{"loacl"}))
|
||||
.isInstanceOf(IllegalStateException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("dev profile 하나 → 기동 허용")
|
||||
void devProfile() {
|
||||
assertThatCode(() -> RuntimeProfileConfig.requireValidProfiles(new String[]{"dev"}))
|
||||
.doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("dev + feature profile → 기동 허용")
|
||||
void featureProfile() {
|
||||
assertThatCode(() -> RuntimeProfileConfig.requireValidProfiles(new String[]{"dev", "metrics"}))
|
||||
.doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("local + prod → 기동 거부")
|
||||
void multipleEnvironmentProfiles() {
|
||||
assertThatThrownBy(() -> RuntimeProfileConfig.requireValidProfiles(new String[]{"local", "prod"}))
|
||||
.isInstanceOf(IllegalStateException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("test profile 하나 → 테스트 기동 허용")
|
||||
void testProfile() {
|
||||
assertThatCode(() -> RuntimeProfileConfig.requireValidProfiles(new String[]{"test"}))
|
||||
.doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("test + prod → 기동 거부")
|
||||
void testAndEnvironmentProfile() {
|
||||
assertThatThrownBy(() -> RuntimeProfileConfig.requireValidProfiles(new String[]{"test", "prod"}))
|
||||
.isInstanceOf(IllegalStateException.class);
|
||||
}
|
||||
}
|
||||
+189
-133
@@ -1,204 +1,263 @@
|
||||
package com.study.course_registration.controller;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.catchThrowableOfType;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalTime;
|
||||
import java.util.Map;
|
||||
|
||||
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.CourseIntegrationTest;
|
||||
import com.study.course_registration.support.Rejections;
|
||||
import com.study.course_registration.support.Scenario;
|
||||
import com.study.course_registration.support.fixture.DatabaseFixture;
|
||||
import com.study.course_registration.support.fixture.DatabaseFixture.RegistrationDataset;
|
||||
import com.study.course_registration.support.fixture.DomainFixtures;
|
||||
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
|
||||
@CourseIntegrationTest
|
||||
@AutoConfigureMockMvc
|
||||
@ActiveProfiles("test")
|
||||
@DisplayName("수강신청 API — 에러 코드가 선언된 상태코드로 나가는가")
|
||||
@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;
|
||||
@Autowired DatabaseFixture fixture;
|
||||
|
||||
private JsonApi api;
|
||||
private User student;
|
||||
private Lesson lesson;
|
||||
private Subject subject;
|
||||
private RegistrationDataset data;
|
||||
|
||||
@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)));
|
||||
|
||||
data = fixture.registrationDataset();
|
||||
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();
|
||||
@DisplayName("POST 신청 성공 → 201")
|
||||
void register201() {
|
||||
Scenario.given(data)
|
||||
.when(current -> api.post(
|
||||
path(current.student().getId()),
|
||||
json(current.lesson().getId())))
|
||||
.then(body -> {
|
||||
assertThat(body.status()).isEqualTo(201);
|
||||
assertThat(body.fieldNames()).containsExactlyInAnyOrder(
|
||||
"registrationId",
|
||||
"userId",
|
||||
"lessonId",
|
||||
"lessonName",
|
||||
"subjectCode",
|
||||
"credit",
|
||||
"registeredAt",
|
||||
"totalCredits");
|
||||
assertThat(body.<String>at("$.userId")).isEqualTo(data.student().getId());
|
||||
assertThat(body.<String>at("$.lessonId")).isEqualTo(data.lesson().getId());
|
||||
assertThat(body.<String>at("$.lessonName")).isEqualTo(data.lesson().getName());
|
||||
assertThat(body.<String>at("$.subjectCode")).isEqualTo(data.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")).isEqualTo("2026-09-21T03:00:00Z");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("취소에 성공하면 204와 빈 본문을 돌려준다")
|
||||
void cancelReturnsNoContent() {
|
||||
JsonBody created = api.post(path(student.getId()), json(lesson.getId()));
|
||||
String registrationId = created.at("$.registrationId");
|
||||
@DisplayName("GET 신청 목록 → 200 + 응답 계약")
|
||||
void registrations200() {
|
||||
api.post(path(data.student().getId()), json(data.lesson().getId()));
|
||||
|
||||
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();
|
||||
Scenario.given(data)
|
||||
.when(current -> api.get(
|
||||
path(current.student().getId())
|
||||
+ "?semesterId="
|
||||
+ current.semester().getId()))
|
||||
.then(body -> {
|
||||
assertThat(body.status()).isEqualTo(200);
|
||||
assertThat(body.fieldNames()).containsExactlyInAnyOrder(
|
||||
"userId",
|
||||
"semesterId",
|
||||
"semesterName",
|
||||
"totalCredits",
|
||||
"maxCredits",
|
||||
"registrations");
|
||||
assertThat(body.<String>at("$.userId")).isEqualTo(data.student().getId());
|
||||
assertThat(body.<String>at("$.semesterId")).isEqualTo(data.semester().getId());
|
||||
assertThat(body.<Integer>at("$.totalCredits")).isEqualTo(3);
|
||||
Map<String, Object> item = body.at("$.registrations[0]");
|
||||
assertThat(item.keySet()).containsExactlyInAnyOrder(
|
||||
"registrationId",
|
||||
"lessonId",
|
||||
"lessonName",
|
||||
"subjectCode",
|
||||
"subjectName",
|
||||
"credit",
|
||||
"professorName",
|
||||
"schedules",
|
||||
"registeredAt");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("없는 사용자로 신청하면 USER_NOT_FOUND — 404로 나간다")
|
||||
void unknownUserIsNotFound() {
|
||||
Scenario.given(api)
|
||||
.when(a -> a.post(path("no-such-user"), json(lesson.getId())))
|
||||
@DisplayName("같은 Idempotency-Key 재시도 → 동일 201 응답")
|
||||
void idempotentPost() {
|
||||
JsonBody first = api.post(
|
||||
path(data.student().getId()),
|
||||
json(data.lesson().getId()),
|
||||
"request-1");
|
||||
|
||||
Scenario.given(first)
|
||||
.when(previous -> api.post(
|
||||
path(data.student().getId()),
|
||||
json(data.lesson().getId()),
|
||||
"request-1"))
|
||||
.then(second -> {
|
||||
assertThat(first.status()).isEqualTo(201);
|
||||
assertThat(second.status()).isEqualTo(201);
|
||||
assertThat(second.<String>at("$.registrationId"))
|
||||
.isEqualTo(first.<String>at("$.registrationId"));
|
||||
assertThat(second.<String>at("$.registeredAt"))
|
||||
.isEqualTo(first.<String>at("$.registeredAt"));
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("같은 Idempotency-Key 다른 강의 → 409")
|
||||
void reusedIdempotencyKey409() {
|
||||
api.post(path(data.student().getId()), json(data.lesson().getId()), "request-2");
|
||||
Subject subject = fixture.subject(DomainFixtures.subject("OTHER"));
|
||||
Lesson other = fixture.lesson(DomainFixtures.lesson(
|
||||
subject,
|
||||
data.professor(),
|
||||
data.semester()));
|
||||
fixture.schedule(DomainFixtures.schedule(other, DayOfWeek.TUESDAY, 13, 15));
|
||||
|
||||
Scenario.given(other)
|
||||
.when(lesson -> api.post(
|
||||
path(data.student().getId()),
|
||||
json(lesson.getId()),
|
||||
"request-2"))
|
||||
.thenRejectedWith(API, RegistrationErrorCode.IDEMPOTENCY_KEY_REUSED);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("DELETE 취소 성공 → 204")
|
||||
void cancel204() {
|
||||
String id = api.post(
|
||||
path(data.student().getId()),
|
||||
json(data.lesson().getId()))
|
||||
.at("$.registrationId");
|
||||
|
||||
Scenario.given(id)
|
||||
.when(registrationId -> api.delete(
|
||||
path(data.student().getId()) + "/" + registrationId))
|
||||
.then(body -> {
|
||||
assertThat(body.status()).isEqualTo(204);
|
||||
assertThat(body.raw()).isEmpty();
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("DELETE 재호출 → 204")
|
||||
void repeatedCancel204() {
|
||||
String id = api.post(
|
||||
path(data.student().getId()),
|
||||
json(data.lesson().getId()))
|
||||
.at("$.registrationId");
|
||||
api.delete(path(data.student().getId()) + "/" + id);
|
||||
|
||||
Scenario.given(id)
|
||||
.when(registrationId -> api.delete(
|
||||
path(data.student().getId()) + "/" + registrationId))
|
||||
.then(body -> assertThat(body.status()).isEqualTo(204));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("없는 사용자 → 404 USER_NOT_FOUND")
|
||||
void user404() {
|
||||
Scenario.given("missing")
|
||||
.when(userId -> api.post(path(userId), json(data.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")))
|
||||
@DisplayName("없는 강의 → 404 LESSON_NOT_FOUND")
|
||||
void lesson404() {
|
||||
Scenario.given("missing")
|
||||
.when(lessonId -> api.post(path(data.student().getId()), json(lessonId)))
|
||||
.thenRejectedWith(API, RegistrationErrorCode.LESSON_NOT_FOUND);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("같은 강의를 두 번 신청하면 ALREADY_REGISTERED — 409로 나간다")
|
||||
void duplicateRegistrationIsConflict() {
|
||||
api.post(path(student.getId()), json(lesson.getId()));
|
||||
@DisplayName("중복 신청 → 409 ALREADY_REGISTERED")
|
||||
void duplicate409() {
|
||||
api.post(path(data.student().getId()), json(data.lesson().getId()));
|
||||
|
||||
Scenario.given(api)
|
||||
.when(a -> a.post(path(student.getId()), json(lesson.getId())))
|
||||
Scenario.given(data)
|
||||
.when(current -> api.post(
|
||||
path(current.student().getId()),
|
||||
json(current.lesson().getId())))
|
||||
.thenRejectedWith(API, RegistrationErrorCode.ALREADY_REGISTERED);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("lessonId가 비면 VALIDATION_ERROR — 400으로 나간다")
|
||||
void blankLessonIdIsBadRequest() {
|
||||
@DisplayName("빈 lessonId → 400 VALIDATION_ERROR")
|
||||
void blankLesson400() {
|
||||
Scenario.given(api)
|
||||
.when(a -> a.post(path(student.getId()), json("")))
|
||||
.when(client -> client.post(path(data.student().getId()), json("")))
|
||||
.thenRejectedWith(API, RegistrationErrorCode.VALIDATION_ERROR);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("본문이 JSON이 아니면 VALIDATION_ERROR — 400으로 나간다")
|
||||
void malformedBodyIsBadRequest() {
|
||||
@DisplayName("잘못된 JSON → 400 VALIDATION_ERROR")
|
||||
void malformed400() {
|
||||
Scenario.given(api)
|
||||
.when(a -> a.post(path(student.getId()), "{not json"))
|
||||
.when(client -> client.post(path(data.student().getId()), "{not json"))
|
||||
.thenRejectedWith(API, RegistrationErrorCode.VALIDATION_ERROR);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("없는 신청 건을 취소하면 REGISTRATION_NOT_FOUND — 404로 나간다 (C1)")
|
||||
void cancelingUnknownRegistrationIsNotFound() {
|
||||
@DisplayName("없는 신청 취소 → 404 REGISTRATION_NOT_FOUND")
|
||||
void registration404() {
|
||||
Scenario.given(api)
|
||||
.when(a -> a.delete(path(student.getId()) + "/no-such-registration"))
|
||||
.when(client -> client.delete(
|
||||
path(data.student().getId()) + "/missing"))
|
||||
.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())));
|
||||
@DisplayName("시간표 없는 강의 → 500 공통 에러")
|
||||
void missingSchedule500() {
|
||||
Subject subject = fixture.subject(DomainFixtures.subject("BROKEN"));
|
||||
Lesson broken = fixture.lesson(DomainFixtures.lesson(
|
||||
subject,
|
||||
data.professor(),
|
||||
data.semester()));
|
||||
|
||||
assertThat(error.code()).isEqualTo("USER_NOT_FOUND");
|
||||
assertThat(error.detail()).isNotBlank();
|
||||
assertThat(error.status()).isEqualTo(404);
|
||||
ApiError error = catchThrowableOfType(
|
||||
ApiError.class,
|
||||
() -> api.post(
|
||||
path(data.student().getId()),
|
||||
json(broken.getId())));
|
||||
|
||||
assertThat(error.status()).isEqualTo(500);
|
||||
assertThat(error.code()).isEqualTo("INTERNAL_SERVER_ERROR");
|
||||
assertThat(error.fieldNames()).containsExactlyInAnyOrder(
|
||||
"code",
|
||||
"message",
|
||||
"timestamp");
|
||||
}
|
||||
|
||||
private static String path(String userId) {
|
||||
@@ -206,15 +265,12 @@ class CourseRegistrationApiTest {
|
||||
}
|
||||
|
||||
private static String json(String lessonId) {
|
||||
return "{\"lessonId\": \"" + 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());
|
||||
assertThat(error.status()).isEqualTo(code.getStatus().value());
|
||||
return code;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
package com.study.course_registration.controller;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
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.test.web.servlet.MockMvc;
|
||||
|
||||
import com.study.course_registration.enums.RegistrationErrorCode;
|
||||
import com.study.course_registration.support.CourseIntegrationTest;
|
||||
import com.study.course_registration.support.Rejections;
|
||||
import com.study.course_registration.support.Scenario;
|
||||
import com.study.course_registration.support.fixture.DatabaseFixture;
|
||||
import com.study.course_registration.support.fixture.DatabaseFixture.RegistrationDataset;
|
||||
import com.study.course_registration.support.http.ApiError;
|
||||
import com.study.course_registration.support.http.JsonApi;
|
||||
import com.study.course_registration.support.http.JsonBody;
|
||||
|
||||
@CourseIntegrationTest
|
||||
@AutoConfigureMockMvc
|
||||
@DisplayName("강의 API")
|
||||
class LessonApiTest {
|
||||
private static final Rejections<ApiError, RegistrationErrorCode> API =
|
||||
Rejections.of(ApiError.class, LessonApiTest::errorCodeOf);
|
||||
|
||||
@Autowired MockMvc mockMvc;
|
||||
@Autowired DatabaseFixture fixture;
|
||||
|
||||
private JsonApi api;
|
||||
private RegistrationDataset data;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
data = fixture.registrationDataset();
|
||||
api = new JsonApi(mockMvc);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("GET 목록 → 200")
|
||||
void list200() {
|
||||
Scenario.given(api)
|
||||
.when(client -> client.get(
|
||||
"/api/v1/lessons?semesterId=" + data.semester().getId()))
|
||||
.then(body -> {
|
||||
assertThat(body.status()).isEqualTo(200);
|
||||
assertThat(body.fieldNames()).containsExactlyInAnyOrder(
|
||||
"page",
|
||||
"size",
|
||||
"totalElements",
|
||||
"lessons");
|
||||
assertThat(body.<Integer>at("$.page")).isZero();
|
||||
assertThat(body.<Integer>at("$.size")).isEqualTo(20);
|
||||
assertThat(body.<Integer>at("$.lessons.length()")).isEqualTo(1);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("GET 상세 → 200")
|
||||
void detail200() {
|
||||
Scenario.given(data.lesson().getId())
|
||||
.when(lessonId -> api.get("/api/v1/lessons/" + lessonId))
|
||||
.then(body -> {
|
||||
assertThat(body.status()).isEqualTo(200);
|
||||
assertThat(body.fieldNames()).contains(
|
||||
"lessonId",
|
||||
"lessonName",
|
||||
"subjectCode",
|
||||
"subjectName",
|
||||
"subjectDescription",
|
||||
"credit",
|
||||
"professorName",
|
||||
"semesterName",
|
||||
"capacity",
|
||||
"enrolledCount",
|
||||
"minGrade",
|
||||
"allowedRole",
|
||||
"registrationStartAt",
|
||||
"registrationEndAt",
|
||||
"schedules");
|
||||
assertThat(body.<String>at("$.lessonId")).isEqualTo(data.lesson().getId());
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("page 상한 초과 → 400 VALIDATION_ERROR")
|
||||
void page400() {
|
||||
Scenario.given(api)
|
||||
.when(client -> client.get("/api/v1/lessons?page=1000001"))
|
||||
.thenRejectedWith(API, RegistrationErrorCode.VALIDATION_ERROR);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("없는 강의 → 404 LESSON_NOT_FOUND")
|
||||
void lesson404() {
|
||||
Scenario.given(api)
|
||||
.when(client -> client.get("/api/v1/lessons/missing"))
|
||||
.thenRejectedWith(API, RegistrationErrorCode.LESSON_NOT_FOUND);
|
||||
}
|
||||
|
||||
private static RegistrationErrorCode errorCodeOf(ApiError error) {
|
||||
RegistrationErrorCode code = RegistrationErrorCode.valueOf(error.code());
|
||||
assertThat(error.status()).isEqualTo(code.getStatus().value());
|
||||
return code;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
package com.study.course_registration.entity;
|
||||
|
||||
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.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.study.course_registration.enums.UserRole;
|
||||
import com.study.course_registration.support.fixture.DomainFixtures;
|
||||
import com.study.course_registration.support.fixture.TestData;
|
||||
|
||||
class EntityInvariantTest {
|
||||
@Test
|
||||
@DisplayName("과목 학점 0 → 생성 거부")
|
||||
void subjectCredit() {
|
||||
assertThatThrownBy(() -> new Subject("과목", "CS0", "", 0))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("강의 정원 0 → 생성 거부")
|
||||
void lessonCapacity() {
|
||||
assertThatThrownBy(() -> new Lesson(
|
||||
"강의",
|
||||
DomainFixtures.subject("CS1"),
|
||||
DomainFixtures.professor(),
|
||||
DomainFixtures.openSemester(),
|
||||
0,
|
||||
null,
|
||||
null))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("시간표 시작 >= 종료 → 생성 거부")
|
||||
void scheduleRange() {
|
||||
Lesson lesson = DomainFixtures.lesson(
|
||||
DomainFixtures.subject("CS2"),
|
||||
DomainFixtures.professor(),
|
||||
DomainFixtures.openSemester());
|
||||
|
||||
assertThatThrownBy(() -> new LessonSchedule(
|
||||
lesson,
|
||||
DayOfWeek.MONDAY,
|
||||
LocalTime.of(11, 0),
|
||||
LocalTime.of(11, 0)))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("학기 신청 시작 >= 종료 → 생성 거부")
|
||||
void semesterWindow() {
|
||||
Instant now = TestData.NOW;
|
||||
|
||||
assertThatThrownBy(() -> new Semester(
|
||||
"학기",
|
||||
TestData.TODAY,
|
||||
TestData.TODAY.plusDays(1),
|
||||
now,
|
||||
now,
|
||||
18))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("사용자 학년 0 → 생성 거부")
|
||||
void userGrade() {
|
||||
assertThatThrownBy(() -> new User("학생", 0L, UserRole.STUDENT))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("과목 이름 공백 → 생성 거부")
|
||||
void subjectName() {
|
||||
assertThatThrownBy(() -> new Subject(" ", "CS", "", 3))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("과목 코드 공백 → 생성 거부")
|
||||
void subjectCode() {
|
||||
assertThatThrownBy(() -> new Subject("과목", " ", "", 3))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("강의 이름 공백 → 생성 거부")
|
||||
void lessonName() {
|
||||
assertThatThrownBy(() -> new Lesson(
|
||||
" ",
|
||||
DomainFixtures.subject("CS"),
|
||||
DomainFixtures.professor(),
|
||||
DomainFixtures.openSemester(),
|
||||
30,
|
||||
null,
|
||||
null))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("강의 최소 학년 0 → 생성 거부")
|
||||
void minGrade() {
|
||||
assertThatThrownBy(() -> new Lesson(
|
||||
"강의",
|
||||
DomainFixtures.subject("CS"),
|
||||
DomainFixtures.professor(),
|
||||
DomainFixtures.openSemester(),
|
||||
30,
|
||||
0L,
|
||||
null))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("학기 종료 < 시작 → 생성 거부")
|
||||
void semesterDates() {
|
||||
LocalDate today = TestData.TODAY;
|
||||
Instant now = TestData.NOW;
|
||||
|
||||
assertThatThrownBy(() -> new Semester(
|
||||
"학기",
|
||||
today,
|
||||
today.minusDays(1),
|
||||
now.minusSeconds(1),
|
||||
now,
|
||||
18))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("학기 최대 학점 0 → 생성 거부")
|
||||
void semesterCredits() {
|
||||
LocalDate today = TestData.TODAY;
|
||||
Instant now = TestData.NOW;
|
||||
|
||||
assertThatThrownBy(() -> new Semester(
|
||||
"학기",
|
||||
today,
|
||||
today.plusDays(1),
|
||||
now.minusSeconds(1),
|
||||
now,
|
||||
0))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("사용자 이름 공백 → 생성 거부")
|
||||
void userName() {
|
||||
assertThatThrownBy(() -> new User(" ", 1L, UserRole.STUDENT))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("같은 신청 두 번 취소 → 도메인 거부")
|
||||
void doubleCancel() {
|
||||
UserLesson registration = DomainFixtures.registration(
|
||||
DomainFixtures.student(2),
|
||||
DomainFixtures.lesson(
|
||||
DomainFixtures.subject("CS"),
|
||||
DomainFixtures.professor(),
|
||||
DomainFixtures.openSemester()));
|
||||
registration.cancel(TestData.NOW);
|
||||
|
||||
assertThatThrownBy(() -> registration.cancel(TestData.NOW))
|
||||
.isInstanceOf(IllegalStateException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Idempotency-Key 공백 → 생성 거부")
|
||||
void idempotencyBlank() {
|
||||
User user = DomainFixtures.student(2);
|
||||
Lesson lesson = DomainFixtures.lesson(
|
||||
DomainFixtures.subject("CS"),
|
||||
DomainFixtures.professor(),
|
||||
DomainFixtures.openSemester());
|
||||
UserLesson registration = DomainFixtures.registration(user, lesson);
|
||||
|
||||
assertThatThrownBy(() -> new RegistrationIdempotency(user, lesson, registration, " ", 3, TestData.NOW.plusSeconds(86400)))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("과목 설명 null → 빈 문자열")
|
||||
void nullSubjectDescription() {
|
||||
Subject subject = new Subject("과목", "CS-N", null, 3);
|
||||
|
||||
assertThat(subject.getDescription()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("교수 이름 공백 → 생성 거부")
|
||||
void professorName() {
|
||||
assertThatThrownBy(() -> new Professor(" "))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("학기 이름 공백 → 생성 거부")
|
||||
void semesterName() {
|
||||
LocalDate today = TestData.TODAY;
|
||||
Instant now = TestData.NOW;
|
||||
|
||||
assertThatThrownBy(() -> new Semester(
|
||||
" ",
|
||||
today,
|
||||
today.plusDays(1),
|
||||
now.minusSeconds(1),
|
||||
now,
|
||||
18))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.study.course_registration.exception;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.ZoneOffset;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import com.study.course_registration.support.fixture.TestData;
|
||||
|
||||
import jakarta.persistence.LockTimeoutException;
|
||||
|
||||
class GlobalExceptionHandlerTest {
|
||||
private final GlobalExceptionHandler handler =
|
||||
new GlobalExceptionHandler(Clock.fixed(TestData.NOW, ZoneOffset.UTC));
|
||||
|
||||
@Test
|
||||
@DisplayName("락 타임아웃 → 503 + Retry-After")
|
||||
void lockTimeout() {
|
||||
ResponseEntity<ErrorResponse> response = handler.handleLockTimeout(new LockTimeoutException());
|
||||
|
||||
assertThat(response.getStatusCode().value()).isEqualTo(503);
|
||||
assertThat(Integer.parseInt(response.getHeaders().getFirst(HttpHeaders.RETRY_AFTER)))
|
||||
.isBetween(1, 3);
|
||||
assertThat(response.getBody().code()).isEqualTo("LOCK_TIMEOUT");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("예상 못한 예외 → 500 공통 에러")
|
||||
void fallback() {
|
||||
ResponseEntity<ErrorResponse> response = handler.handleUnexpected(new RuntimeException("boom"));
|
||||
|
||||
assertThat(response.getStatusCode().value()).isEqualTo(500);
|
||||
assertThat(response.getBody().code()).isEqualTo("INTERNAL_SERVER_ERROR");
|
||||
assertThat(response.getBody().timestamp()).isEqualTo(TestData.NOW);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package com.study.course_registration.repository;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
|
||||
import org.hibernate.Hibernate;
|
||||
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.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
|
||||
import com.study.course_registration.entity.Lesson;
|
||||
import com.study.course_registration.entity.Subject;
|
||||
import com.study.course_registration.support.PessimisticLockProbe;
|
||||
import com.study.course_registration.support.PostgresIntegrationTest;
|
||||
import com.study.course_registration.support.Scenario;
|
||||
import com.study.course_registration.support.fixture.DatabaseFixture;
|
||||
import com.study.course_registration.support.fixture.DatabaseFixture.RegistrationDataset;
|
||||
import com.study.course_registration.support.fixture.DomainFixtures;
|
||||
|
||||
class LessonRepositoryTest extends PostgresIntegrationTest {
|
||||
@Autowired DatabaseFixture fixture;
|
||||
@Autowired LessonRepository repository;
|
||||
@Autowired PlatformTransactionManager transactionManager;
|
||||
|
||||
private RegistrationDataset data;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
data = fixture.registrationDataset();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("findByIdForUpdate → PostgreSQL lesson row lock")
|
||||
void pessimisticLock() throws Exception {
|
||||
PessimisticLockProbe.assertSecondTransactionBlocks(
|
||||
transactionManager,
|
||||
() -> repository.findByIdForUpdate(data.lesson().getId()).orElseThrow(),
|
||||
() -> repository.findByIdForUpdate(data.lesson().getId()).orElseThrow());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("상세 조회 → subject·professor·semester graph 초기화")
|
||||
void detailGraph() {
|
||||
Scenario.given(data.lesson().getId())
|
||||
.when(id -> repository.findDetailedById(id).orElseThrow())
|
||||
.then(lesson -> {
|
||||
assertThat(Hibernate.isInitialized(lesson.getSubject())).isTrue();
|
||||
assertThat(Hibernate.isInitialized(lesson.getProfessor())).isTrue();
|
||||
assertThat(Hibernate.isInitialized(lesson.getSemester())).isTrue();
|
||||
assertThat(lesson.getSubject().getCode()).isEqualTo(data.subject().getCode());
|
||||
assertThat(lesson.getProfessor().getId()).isEqualTo(data.professor().getId());
|
||||
assertThat(lesson.getSemester().getId()).isEqualTo(data.semester().getId());
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("학기 조회 → 이름·ID 순 정렬")
|
||||
void semesterPagingAndSort() {
|
||||
Subject subject = fixture.subject(DomainFixtures.subject("CS200"));
|
||||
Lesson lesson = fixture.lesson(DomainFixtures.lesson(
|
||||
null, "AAA 강의", subject, data.professor(), data.semester(), 30, null, null));
|
||||
fixture.schedule(DomainFixtures.schedule(lesson, DayOfWeek.TUESDAY, 9, 11));
|
||||
|
||||
Scenario.given(data)
|
||||
.when(current -> repository.findBySemester_Id(
|
||||
current.semester().getId(),
|
||||
PageRequest.of(0, 20, Sort.by("name").ascending().and(Sort.by("id").ascending()))))
|
||||
.then(page -> assertThat(page.getContent())
|
||||
.extracting(Lesson::getName)
|
||||
.containsExactly("AAA 강의", "CS101 강의"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("과목 필터 → 해당 과목 강의만 반환")
|
||||
void subjectFilter() {
|
||||
Subject other = fixture.subject(DomainFixtures.subject("CS300"));
|
||||
Lesson lesson = fixture.lesson(DomainFixtures.lesson(other, data.professor(), data.semester()));
|
||||
fixture.schedule(DomainFixtures.schedule(lesson, DayOfWeek.FRIDAY, 9, 11));
|
||||
|
||||
Scenario.given(other.getId())
|
||||
.when(subjectId -> repository.findBySemester_IdAndSubject_Id(
|
||||
data.semester().getId(), subjectId, PageRequest.of(0, 20)))
|
||||
.then(page -> assertThat(page.getContent())
|
||||
.extracting(Lesson::getId)
|
||||
.containsExactly(lesson.getId()));
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
package com.study.course_registration.repository;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
import java.util.List;
|
||||
|
||||
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 com.study.course_registration.entity.Lesson;
|
||||
import com.study.course_registration.entity.LessonSchedule;
|
||||
import com.study.course_registration.entity.Subject;
|
||||
import com.study.course_registration.support.PostgresIntegrationTest;
|
||||
import com.study.course_registration.support.Scenario;
|
||||
import com.study.course_registration.support.fixture.DatabaseFixture;
|
||||
import com.study.course_registration.support.fixture.DatabaseFixture.RegistrationDataset;
|
||||
import com.study.course_registration.support.fixture.DomainFixtures;
|
||||
|
||||
class LessonScheduleRepositoryTest extends PostgresIntegrationTest {
|
||||
@Autowired DatabaseFixture fixture;
|
||||
@Autowired LessonScheduleRepository repository;
|
||||
|
||||
private RegistrationDataset data;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
data = fixture.registrationDataset();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("lesson IDs bulk 조회 → 요일·시작시각 순 정렬")
|
||||
void bulkAndOrdering() {
|
||||
Subject subject = fixture.subject(DomainFixtures.subject("CS200"));
|
||||
Lesson other = fixture.lesson(DomainFixtures.lesson(subject, data.professor(), data.semester()));
|
||||
fixture.schedule(DomainFixtures.schedule(other, DayOfWeek.WEDNESDAY, 13, 15));
|
||||
fixture.schedule(DomainFixtures.schedule(other, DayOfWeek.TUESDAY, 15, 17));
|
||||
fixture.schedule(DomainFixtures.schedule(other, DayOfWeek.TUESDAY, 9, 11));
|
||||
|
||||
List<String> lessonIds = List.of(data.lesson().getId(), other.getId());
|
||||
|
||||
Scenario.given(lessonIds)
|
||||
.when(repository::findByLesson_IdInOrderByDayOfWeekAscStartTimeAsc)
|
||||
.then(schedules -> assertThat(schedules)
|
||||
.extracting(
|
||||
schedule -> schedule.getDayOfWeek().name(),
|
||||
schedule -> schedule.getStartTime().toString())
|
||||
.containsExactly(
|
||||
org.assertj.core.groups.Tuple.tuple("MONDAY", "09:00"),
|
||||
org.assertj.core.groups.Tuple.tuple("TUESDAY", "09:00"),
|
||||
org.assertj.core.groups.Tuple.tuple("TUESDAY", "15:00"),
|
||||
org.assertj.core.groups.Tuple.tuple("WEDNESDAY", "13:00")));
|
||||
}
|
||||
}
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
package com.study.course_registration.repository;
|
||||
|
||||
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 org.hibernate.Hibernate;
|
||||
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.dao.DataIntegrityViolationException;
|
||||
|
||||
import com.study.course_registration.entity.Lesson;
|
||||
import com.study.course_registration.entity.RegistrationIdempotency;
|
||||
import com.study.course_registration.entity.Subject;
|
||||
import com.study.course_registration.entity.UserLesson;
|
||||
import com.study.course_registration.support.PostgresIntegrationTest;
|
||||
import com.study.course_registration.support.Scenario;
|
||||
import com.study.course_registration.support.fixture.DatabaseFixture;
|
||||
import com.study.course_registration.support.fixture.DatabaseFixture.RegistrationDataset;
|
||||
import com.study.course_registration.support.fixture.DomainFixtures;
|
||||
import com.study.course_registration.support.fixture.TestData;
|
||||
|
||||
class RegistrationIdempotencyRepositoryTest extends PostgresIntegrationTest {
|
||||
@Autowired DatabaseFixture fixture;
|
||||
@Autowired RegistrationIdempotencyRepository repository;
|
||||
|
||||
private RegistrationDataset data;
|
||||
private UserLesson registration;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
data = fixture.registrationDataset();
|
||||
registration = fixture.registration(
|
||||
DomainFixtures.registration(data.student(), data.lesson()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("userId + key + 유효기간 조회 → 연관 graph와 lifecycle 로드")
|
||||
void lookupGraph() {
|
||||
Instant expiresAt = TestData.NOW.plusSeconds(86400);
|
||||
repository.saveAndFlush(idempotency("request-1", registration, data.lesson(), expiresAt));
|
||||
|
||||
Scenario.given("request-1")
|
||||
.when(key -> repository
|
||||
.findByUser_IdAndIdempotencyKeyAndExpiresAtAfter(
|
||||
data.student().getId(),
|
||||
key,
|
||||
TestData.NOW)
|
||||
.orElseThrow())
|
||||
.then(stored -> {
|
||||
assertThat(Hibernate.isInitialized(stored.getUser())).isTrue();
|
||||
assertThat(Hibernate.isInitialized(stored.getLesson())).isTrue();
|
||||
assertThat(Hibernate.isInitialized(stored.getLesson().getSubject())).isTrue();
|
||||
assertThat(Hibernate.isInitialized(stored.getRegistration())).isTrue();
|
||||
assertThat(stored.getCreatedAt()).isNotNull();
|
||||
assertThat(stored.getExpiresAt()).isEqualTo(expiresAt);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("만료 key 삭제 → 같은 user + key 재사용 가능")
|
||||
void expiredKeyCanBeRemoved() {
|
||||
Instant expiredAt = TestData.NOW.minusSeconds(1);
|
||||
repository.saveAndFlush(idempotency("request-expired", registration, data.lesson(), expiredAt));
|
||||
|
||||
Scenario.given("request-expired")
|
||||
.when(key -> repository.deleteExpiredKey(
|
||||
data.student().getId(),
|
||||
key,
|
||||
TestData.NOW))
|
||||
.then(deleted -> {
|
||||
assertThat(deleted).isEqualTo(1);
|
||||
assertThat(repository.findAll()).isEmpty();
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("만료 전체 정리 → expiresAt 지난 행만 삭제")
|
||||
void deleteExpired() {
|
||||
repository.saveAndFlush(idempotency(
|
||||
"expired",
|
||||
registration,
|
||||
data.lesson(),
|
||||
TestData.NOW.minusSeconds(1)));
|
||||
|
||||
Subject subject = fixture.subject(DomainFixtures.subject("FRESH"));
|
||||
Lesson freshLesson = fixture.lesson(
|
||||
DomainFixtures.lesson(subject, data.professor(), data.semester()));
|
||||
fixture.schedule(DomainFixtures.schedule(freshLesson, DayOfWeek.TUESDAY, 13, 15));
|
||||
UserLesson freshRegistration = fixture.registration(
|
||||
DomainFixtures.registration(data.student(), freshLesson));
|
||||
repository.saveAndFlush(new RegistrationIdempotency(
|
||||
data.student(),
|
||||
freshLesson,
|
||||
freshRegistration,
|
||||
"fresh",
|
||||
6,
|
||||
TestData.NOW.plusSeconds(86400)));
|
||||
|
||||
Scenario.given(TestData.NOW)
|
||||
.when(repository::deleteExpired)
|
||||
.then(deleted -> {
|
||||
assertThat(deleted).isEqualTo(1);
|
||||
assertThat(repository.findAll())
|
||||
.extracting(RegistrationIdempotency::getIdempotencyKey)
|
||||
.containsExactly("fresh");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("같은 user + key → DB unique 거부")
|
||||
void userKeyUnique() {
|
||||
repository.saveAndFlush(idempotency(
|
||||
"request-1",
|
||||
registration,
|
||||
data.lesson(),
|
||||
TestData.NOW.plusSeconds(86400)));
|
||||
|
||||
Subject subject = fixture.subject(DomainFixtures.subject("OTHER"));
|
||||
Lesson otherLesson = fixture.lesson(
|
||||
DomainFixtures.lesson(subject, data.professor(), data.semester()));
|
||||
fixture.schedule(DomainFixtures.schedule(otherLesson, DayOfWeek.TUESDAY, 13, 15));
|
||||
UserLesson otherRegistration =
|
||||
fixture.registration(DomainFixtures.registration(data.student(), otherLesson));
|
||||
|
||||
assertThatThrownBy(() -> repository.saveAndFlush(new RegistrationIdempotency(
|
||||
data.student(),
|
||||
otherLesson,
|
||||
otherRegistration,
|
||||
"request-1",
|
||||
6,
|
||||
TestData.NOW.plusSeconds(86400))))
|
||||
.isInstanceOf(DataIntegrityViolationException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("같은 registration + 다른 key → DB unique 거부")
|
||||
void registrationUnique() {
|
||||
repository.saveAndFlush(idempotency(
|
||||
"request-1",
|
||||
registration,
|
||||
data.lesson(),
|
||||
TestData.NOW.plusSeconds(86400)));
|
||||
|
||||
assertThatThrownBy(() -> repository.saveAndFlush(new RegistrationIdempotency(
|
||||
data.student(),
|
||||
data.lesson(),
|
||||
registration,
|
||||
"request-2",
|
||||
3,
|
||||
TestData.NOW.plusSeconds(86400))))
|
||||
.isInstanceOf(DataIntegrityViolationException.class);
|
||||
}
|
||||
|
||||
private RegistrationIdempotency idempotency(
|
||||
String key,
|
||||
UserLesson target,
|
||||
Lesson lesson,
|
||||
Instant expiresAt) {
|
||||
return new RegistrationIdempotency(
|
||||
data.student(),
|
||||
lesson,
|
||||
target,
|
||||
key,
|
||||
3,
|
||||
expiresAt);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.study.course_registration.repository;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
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 com.study.course_registration.entity.Semester;
|
||||
import com.study.course_registration.support.PostgresIntegrationTest;
|
||||
import com.study.course_registration.support.Scenario;
|
||||
import com.study.course_registration.support.fixture.DatabaseFixture;
|
||||
import com.study.course_registration.support.fixture.DomainFixtures;
|
||||
import com.study.course_registration.support.fixture.TestData;
|
||||
|
||||
class SemesterRepositoryTest extends PostgresIntegrationTest {
|
||||
@Autowired DatabaseFixture fixture;
|
||||
@Autowired SemesterRepository repository;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
fixture.reset();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("신청 기간 포함 조회 → 활성 학기 반환")
|
||||
void findRegistrationWindow() {
|
||||
Semester semester = fixture.semester(DomainFixtures.futureAcademicSemesterWithOpenRegistration());
|
||||
|
||||
Scenario.given(TestData.NOW)
|
||||
.when(now -> repository
|
||||
.findByRegistrationStartAtLessThanEqualAndRegistrationEndAtGreaterThanEqual(now, now))
|
||||
.then(result -> assertThat(result)
|
||||
.extracting(Semester::getId)
|
||||
.containsExactly(semester.getId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("학사 기간 포함 조회 → 진행 학기 반환")
|
||||
void findAcademicWindow() {
|
||||
Semester semester = fixture.semester(DomainFixtures.academicSemester("academic"));
|
||||
|
||||
Scenario.given(TestData.TODAY)
|
||||
.when(today -> repository.findByStartDateLessThanEqualAndEndDateGreaterThanEqual(today, today))
|
||||
.then(result -> assertThat(result)
|
||||
.extracting(Semester::getId)
|
||||
.containsExactly(semester.getId()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
package com.study.course_registration.repository;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
import java.util.List;
|
||||
|
||||
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.dao.DataIntegrityViolationException;
|
||||
|
||||
import com.study.course_registration.entity.Lesson;
|
||||
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.support.PostgresIntegrationTest;
|
||||
import com.study.course_registration.support.Scenario;
|
||||
import com.study.course_registration.support.fixture.DatabaseFixture;
|
||||
import com.study.course_registration.support.fixture.DatabaseFixture.RegistrationDataset;
|
||||
import com.study.course_registration.support.fixture.DomainFixtures;
|
||||
import com.study.course_registration.support.fixture.TestData;
|
||||
|
||||
class UserLessonRepositoryTest extends PostgresIntegrationTest {
|
||||
@Autowired DatabaseFixture fixture;
|
||||
@Autowired UserLessonRepository repository;
|
||||
|
||||
private RegistrationDataset data;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
data = fixture.registrationDataset();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("유효 신청 조회 → 같은 학기·미취소만 반환")
|
||||
void activeBySemester() {
|
||||
fixture.registration(DomainFixtures.registration(data.student(), data.lesson()));
|
||||
|
||||
Semester otherSemester = fixture.semester(DomainFixtures.semester(
|
||||
null,
|
||||
"2027-1",
|
||||
TestData.TODAY.plusDays(100),
|
||||
TestData.TODAY.plusDays(200),
|
||||
-3600,
|
||||
3600,
|
||||
18));
|
||||
Subject otherSubject = fixture.subject(DomainFixtures.subject("OTHER"));
|
||||
Lesson otherLesson = fixture.lesson(
|
||||
DomainFixtures.lesson(otherSubject, data.professor(), otherSemester));
|
||||
fixture.schedule(DomainFixtures.schedule(otherLesson, DayOfWeek.TUESDAY, 9, 11));
|
||||
fixture.registration(DomainFixtures.registration(data.student(), otherLesson));
|
||||
|
||||
Subject canceledSubject = fixture.subject(DomainFixtures.subject("CANCEL"));
|
||||
Lesson canceledLesson = fixture.lesson(
|
||||
DomainFixtures.lesson(canceledSubject, data.professor(), data.semester()));
|
||||
fixture.schedule(DomainFixtures.schedule(canceledLesson, DayOfWeek.WEDNESDAY, 9, 11));
|
||||
UserLesson canceled = fixture.registration(
|
||||
DomainFixtures.registration(data.student(), canceledLesson));
|
||||
canceled.cancel(TestData.NOW);
|
||||
repository.saveAndFlush(canceled);
|
||||
|
||||
Scenario.given(data)
|
||||
.when(current -> repository.findActiveByUserIdAndSemesterId(
|
||||
current.student().getId(),
|
||||
current.semester().getId()))
|
||||
.then(result -> assertThat(result)
|
||||
.extracting(registration -> registration.getLesson().getId())
|
||||
.containsExactly(data.lesson().getId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("유효 신청 중복 → DB unique 거부")
|
||||
void activeDuplicateIsRejected() {
|
||||
fixture.registration(DomainFixtures.registration(data.student(), data.lesson()));
|
||||
|
||||
assertThatThrownBy(() -> fixture.registration(
|
||||
DomainFixtures.registration(data.student(), data.lesson())))
|
||||
.isInstanceOf(DataIntegrityViolationException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("취소 후 같은 강의 재신청 → 허용")
|
||||
void canceledThenRegisterAgain() {
|
||||
UserLesson first = fixture.registration(
|
||||
DomainFixtures.registration(data.student(), data.lesson()));
|
||||
first.cancel(TestData.NOW);
|
||||
repository.saveAndFlush(first);
|
||||
|
||||
Scenario.given(first)
|
||||
.when(previous -> fixture.registration(
|
||||
DomainFixtures.registration(data.student(), data.lesson())))
|
||||
.then(second -> {
|
||||
assertThat(second.getId()).isNotEqualTo(first.getId());
|
||||
assertThat(repository.countByLesson_IdAndCanceledAtIsNull(data.lesson().getId()))
|
||||
.isEqualTo(1);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("강의별 신청 수 집계 → 취소 건 제외")
|
||||
void aggregateCountsExcludeCanceled() {
|
||||
fixture.registration(DomainFixtures.registration(data.student(), data.lesson()));
|
||||
User other = fixture.user(DomainFixtures.student(3));
|
||||
UserLesson canceled = fixture.registration(
|
||||
DomainFixtures.registration(other, data.lesson()));
|
||||
canceled.cancel(TestData.NOW);
|
||||
repository.saveAndFlush(canceled);
|
||||
|
||||
Scenario.given(List.of(data.lesson().getId()))
|
||||
.when(repository::countActiveByLessonIds)
|
||||
.then(counts -> assertThat(counts)
|
||||
.singleElement()
|
||||
.satisfies(count -> {
|
||||
assertThat(count.getLessonId()).isEqualTo(data.lesson().getId());
|
||||
assertThat(count.getEnrolledCount()).isEqualTo(1);
|
||||
}));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("취소 대상 projection → userId·lessonId 반환")
|
||||
void targetProjection() {
|
||||
UserLesson registration = fixture.registration(
|
||||
DomainFixtures.registration(data.student(), data.lesson()));
|
||||
|
||||
Scenario.given(registration.getId())
|
||||
.when(id -> repository.findTargetById(id).orElseThrow())
|
||||
.then(target -> {
|
||||
assertThat(target.getUserId()).isEqualTo(data.student().getId());
|
||||
assertThat(target.getLessonId()).isEqualTo(data.lesson().getId());
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.study.course_registration.repository;
|
||||
|
||||
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.transaction.PlatformTransactionManager;
|
||||
|
||||
import com.study.course_registration.support.PessimisticLockProbe;
|
||||
import com.study.course_registration.support.PostgresIntegrationTest;
|
||||
import com.study.course_registration.support.fixture.DatabaseFixture;
|
||||
import com.study.course_registration.support.fixture.DatabaseFixture.RegistrationDataset;
|
||||
|
||||
class UserRepositoryTest extends PostgresIntegrationTest {
|
||||
@Autowired DatabaseFixture fixture;
|
||||
@Autowired UserRepository repository;
|
||||
@Autowired PlatformTransactionManager transactionManager;
|
||||
|
||||
private RegistrationDataset data;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
data = fixture.registrationDataset();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("findByIdForUpdate → PostgreSQL user row lock")
|
||||
void pessimisticLock() throws Exception {
|
||||
PessimisticLockProbe.assertSecondTransactionBlocks(
|
||||
transactionManager,
|
||||
() -> repository.findByIdForUpdate(data.student().getId()).orElseThrow(),
|
||||
() -> repository.findByIdForUpdate(data.student().getId()).orElseThrow());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.study.course_registration.seeder;
|
||||
|
||||
import java.time.Clock;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
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.entity.Semester;
|
||||
import com.study.course_registration.repository.LessonRepository;
|
||||
import com.study.course_registration.repository.SemesterRepository;
|
||||
import com.study.course_registration.repository.UserRepository;
|
||||
|
||||
@SpringBootTest
|
||||
@ActiveProfiles("local")
|
||||
class DataSeederTest {
|
||||
@Autowired DataSeeder seeder;
|
||||
@Autowired Clock clock;
|
||||
@Autowired SemesterRepository semesters;
|
||||
@Autowired LessonRepository lessons;
|
||||
@Autowired UserRepository users;
|
||||
|
||||
@Test
|
||||
@DisplayName("local seed → 학기 1·강의 7·사용자 3")
|
||||
void loadsDataset() {
|
||||
assertThat(semesters.count()).isEqualTo(1);
|
||||
assertThat(lessons.count()).isEqualTo(7);
|
||||
assertThat(users.count()).isEqualTo(3);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
@DisplayName("local seed → 신청 기간이 현재 시각 포함")
|
||||
void registrationWindowContainsNow() {
|
||||
Semester semester = semesters.findById(DataSeeder.SEMESTER_ID).orElseThrow();
|
||||
|
||||
assertThat(semester.getRegistrationStartAt()).isBefore(clock.instant());
|
||||
assertThat(semester.getRegistrationEndAt()).isAfter(clock.instant());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("seed 재실행 → 데이터 중복 없음")
|
||||
void rerunIsIdempotent() throws Exception {
|
||||
seeder.run();
|
||||
|
||||
assertThat(semesters.count()).isEqualTo(1);
|
||||
assertThat(lessons.count()).isEqualTo(7);
|
||||
assertThat(users.count()).isEqualTo(3);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.study.course_registration.seeder;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class SeedTableTest {
|
||||
@Test
|
||||
@DisplayName("TSV 읽기 → 문자열·nullable·숫자 변환")
|
||||
void read() {
|
||||
SeedTable.Row row = SeedTable.read("seed/test/valid.tsv").getFirst();
|
||||
|
||||
assertThat(row.text("name")).isEqualTo("alpha");
|
||||
assertThat(row.nullable("optional")).isNull();
|
||||
assertThat(row.integer("number")).isEqualTo(3);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("컬럼 수 불일치 → 로드 실패")
|
||||
void malformed() {
|
||||
assertThatThrownBy(() -> SeedTable.read("seed/test/malformed.tsv"))
|
||||
.isInstanceOf(IllegalStateException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("리소스 없음 → 로드 실패")
|
||||
void missing() {
|
||||
assertThatThrownBy(() -> SeedTable.read("seed/test/missing.tsv"))
|
||||
.isInstanceOf(IllegalStateException.class);
|
||||
}
|
||||
}
|
||||
+145
-114
@@ -3,9 +3,6 @@ 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;
|
||||
@@ -16,34 +13,27 @@ import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
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.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.*;
|
||||
import com.study.course_registration.repository.UserLessonRepository;
|
||||
import com.study.course_registration.support.PostgresIntegrationTest;
|
||||
import com.study.course_registration.support.Scenario;
|
||||
import com.study.course_registration.support.fixture.DatabaseFixture;
|
||||
import com.study.course_registration.support.fixture.DomainFixtures;
|
||||
|
||||
@SpringBootTest
|
||||
@ActiveProfiles("test")
|
||||
class CourseRegistrationConcurrencyIntegrationTest {
|
||||
class CourseRegistrationConcurrencyIntegrationTest extends PostgresIntegrationTest {
|
||||
@Autowired CourseRegistrationService service;
|
||||
@Autowired UserLessonRepository userLessonRepository;
|
||||
@Autowired LessonScheduleRepository lessonScheduleRepository;
|
||||
@Autowired LessonRepository lessonRepository;
|
||||
@Autowired SubjectRepository subjectRepository;
|
||||
@Autowired ProfessorRepository professorRepository;
|
||||
@Autowired SemesterRepository semesterRepository;
|
||||
@Autowired UserRepository userRepository;
|
||||
@Autowired DatabaseFixture fixture;
|
||||
@Autowired UserLessonRepository registrations;
|
||||
|
||||
private ExecutorService executor;
|
||||
private Semester semester;
|
||||
@@ -51,11 +41,9 @@ class CourseRegistrationConcurrencyIntegrationTest {
|
||||
|
||||
@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", "교수"));
|
||||
fixture.reset();
|
||||
semester = fixture.semester(DomainFixtures.openSemester());
|
||||
professor = fixture.professor(DomainFixtures.professor());
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
@@ -67,108 +55,123 @@ class CourseRegistrationConcurrencyIntegrationTest {
|
||||
}
|
||||
|
||||
@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);
|
||||
@DisplayName("정원 1 + 동시 10명 → 성공 1")
|
||||
void capacityOne() {
|
||||
Lesson lesson = fixture.scheduledLesson(
|
||||
semester, professor, "CAP1", 3, 1, DayOfWeek.MONDAY, 9, 11);
|
||||
List<User> users = fixture.students(10, "cap1-");
|
||||
List<ThrowingAction> actions = users.stream()
|
||||
.<ThrowingAction>map(user -> () -> service.register(
|
||||
user.getId(),
|
||||
new CourseRegistrationRequest(lesson.getId())))
|
||||
.toList();
|
||||
|
||||
Scenario.given(actions)
|
||||
.when(this::run)
|
||||
.then(outcome -> {
|
||||
assertThat(outcome.acceptedCount()).isEqualTo(1);
|
||||
assertThat(outcome.rejectedCount(RegistrationErrorCode.CAPACITY_EXCEEDED)).isEqualTo(9);
|
||||
assertThat(registrations.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);
|
||||
@DisplayName("정원 30 + 동시 50명 → 성공 30")
|
||||
void capacityThirty() {
|
||||
Lesson lesson = fixture.scheduledLesson(
|
||||
semester, professor, "CAP30", 3, 30, DayOfWeek.THURSDAY, 9, 11);
|
||||
List<User> users = fixture.students(50, "cap30-");
|
||||
List<ThrowingAction> actions = users.stream()
|
||||
.<ThrowingAction>map(user -> () -> service.register(
|
||||
user.getId(),
|
||||
new CourseRegistrationRequest(lesson.getId())))
|
||||
.toList();
|
||||
|
||||
Scenario.given(actions)
|
||||
.when(this::run)
|
||||
.then(outcome -> {
|
||||
assertThat(outcome.acceptedCount()).isEqualTo(30);
|
||||
assertThat(outcome.rejectedCount(RegistrationErrorCode.CAPACITY_EXCEEDED)).isEqualTo(20);
|
||||
assertThat(registrations.countByLesson_IdAndCanceledAtIsNull(lesson.getId())).isEqualTo(30);
|
||||
});
|
||||
}
|
||||
|
||||
@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);
|
||||
@DisplayName("동일 학생 + 잔여 3학점 + 동시 2강의 → 성공 1")
|
||||
void creditLimit() {
|
||||
fixture.reset();
|
||||
semester = fixture.semester(DomainFixtures.openSemester(3));
|
||||
professor = fixture.professor(DomainFixtures.professor());
|
||||
User user = fixture.user(DomainFixtures.student(2));
|
||||
Lesson first = fixture.scheduledLesson(
|
||||
semester, professor, "CR1", 3, 30, DayOfWeek.MONDAY, 9, 11);
|
||||
Lesson second = fixture.scheduledLesson(
|
||||
semester, professor, "CR2", 3, 30, DayOfWeek.TUESDAY, 9, 11);
|
||||
|
||||
Scenario.given(List.<ThrowingAction>of(
|
||||
() -> service.register(
|
||||
user.getId(),
|
||||
new CourseRegistrationRequest(first.getId())),
|
||||
() -> service.register(
|
||||
user.getId(),
|
||||
new CourseRegistrationRequest(second.getId()))))
|
||||
.when(this::run)
|
||||
.then(outcome -> {
|
||||
assertThat(outcome.acceptedCount()).isEqualTo(1);
|
||||
assertThat(outcome.rejectedCount(RegistrationErrorCode.CREDIT_LIMIT_EXCEEDED)).isEqualTo(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);
|
||||
@DisplayName("동일 학생 + 겹치는 2강의 동시 신청 → 성공 1")
|
||||
void scheduleConflict() {
|
||||
User user = fixture.user(DomainFixtures.student(2));
|
||||
Lesson first = fixture.scheduledLesson(
|
||||
semester, professor, "SC1", 3, 30, DayOfWeek.MONDAY, 9, 11);
|
||||
Lesson second = fixture.scheduledLesson(
|
||||
semester, professor, "SC2", 3, 30, DayOfWeek.MONDAY, 10, 12);
|
||||
|
||||
Scenario.given(List.<ThrowingAction>of(
|
||||
() -> service.register(
|
||||
user.getId(),
|
||||
new CourseRegistrationRequest(first.getId())),
|
||||
() -> service.register(
|
||||
user.getId(),
|
||||
new CourseRegistrationRequest(second.getId()))))
|
||||
.when(this::run)
|
||||
.then(outcome -> {
|
||||
assertThat(outcome.acceptedCount()).isEqualTo(1);
|
||||
assertThat(outcome.rejectedCount(RegistrationErrorCode.SCHEDULE_CONFLICT)).isEqualTo(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);
|
||||
@DisplayName("동일 학생 + 동일 강의 동시 신청 → 성공 1")
|
||||
void duplicateLesson() {
|
||||
User user = fixture.user(DomainFixtures.student(2));
|
||||
Lesson lesson = fixture.scheduledLesson(
|
||||
semester, professor, "DUP", 3, 30, DayOfWeek.WEDNESDAY, 9, 11);
|
||||
|
||||
Scenario.given(List.<ThrowingAction>of(
|
||||
() -> service.register(
|
||||
user.getId(),
|
||||
new CourseRegistrationRequest(lesson.getId())),
|
||||
() -> service.register(
|
||||
user.getId(),
|
||||
new CourseRegistrationRequest(lesson.getId()))))
|
||||
.when(this::run)
|
||||
.then(outcome -> {
|
||||
assertThat(outcome.acceptedCount()).isEqualTo(1);
|
||||
assertThat(outcome.rejectedCount(RegistrationErrorCode.ALREADY_REGISTERED)).isEqualTo(1);
|
||||
});
|
||||
}
|
||||
|
||||
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 {
|
||||
private ConcurrentOutcome run(List<ThrowingAction> actions) {
|
||||
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<AttemptResult> results = Collections.synchronizedList(new ArrayList<>());
|
||||
List<Throwable> unexpected = Collections.synchronizedList(new ArrayList<>());
|
||||
|
||||
for (ThrowingAction action : actions) {
|
||||
@@ -177,9 +180,9 @@ class CourseRegistrationConcurrencyIntegrationTest {
|
||||
try {
|
||||
start.await();
|
||||
action.run();
|
||||
results.add(null);
|
||||
results.add(new Accepted());
|
||||
} catch (RegistrationException exception) {
|
||||
results.add(exception.getErrorCode());
|
||||
results.add(new Rejected(exception.getErrorCode()));
|
||||
} catch (Throwable throwable) {
|
||||
unexpected.add(throwable);
|
||||
} finally {
|
||||
@@ -188,11 +191,39 @@ class CourseRegistrationConcurrencyIntegrationTest {
|
||||
});
|
||||
}
|
||||
|
||||
assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue();
|
||||
start.countDown();
|
||||
assertThat(done.await(30, TimeUnit.SECONDS)).isTrue();
|
||||
try {
|
||||
assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue();
|
||||
start.countDown();
|
||||
assertThat(done.await(30, TimeUnit.SECONDS)).isTrue();
|
||||
} catch (InterruptedException interrupted) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new AssertionError("동시성 테스트가 중단되었습니다.", interrupted);
|
||||
}
|
||||
assertThat(unexpected).isEmpty();
|
||||
return results;
|
||||
return new ConcurrentOutcome(List.copyOf(results));
|
||||
}
|
||||
|
||||
private sealed interface AttemptResult permits Accepted, Rejected {
|
||||
}
|
||||
|
||||
private record Accepted() implements AttemptResult {
|
||||
}
|
||||
|
||||
private record Rejected(RegistrationErrorCode code) implements AttemptResult {
|
||||
}
|
||||
|
||||
private record ConcurrentOutcome(List<AttemptResult> attempts) {
|
||||
long acceptedCount() {
|
||||
return attempts.stream().filter(Accepted.class::isInstance).count();
|
||||
}
|
||||
|
||||
long rejectedCount(RegistrationErrorCode code) {
|
||||
return attempts.stream()
|
||||
.filter(Rejected.class::isInstance)
|
||||
.map(Rejected.class::cast)
|
||||
.filter(rejected -> rejected.code() == code)
|
||||
.count();
|
||||
}
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
|
||||
+220
-110
@@ -1,171 +1,281 @@
|
||||
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.DisplayName;
|
||||
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.dto.registration.RegistrationListResponse;
|
||||
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;
|
||||
import com.study.course_registration.support.PostgresIntegrationTest;
|
||||
import com.study.course_registration.support.Rejections;
|
||||
import com.study.course_registration.support.Scenario;
|
||||
import com.study.course_registration.support.fixture.DatabaseFixture;
|
||||
import com.study.course_registration.support.fixture.DatabaseFixture.RegistrationDataset;
|
||||
import com.study.course_registration.support.fixture.DomainFixtures;
|
||||
import com.study.course_registration.support.fixture.TestData;
|
||||
|
||||
class CourseRegistrationServiceIntegrationTest extends PostgresIntegrationTest {
|
||||
private static final Rejections<RegistrationException, RegistrationErrorCode> REJECTIONS =
|
||||
Rejections.of(RegistrationException.class, RegistrationException::getErrorCode);
|
||||
|
||||
@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;
|
||||
@Autowired DatabaseFixture fixture;
|
||||
@Autowired UserLessonRepository registrations;
|
||||
|
||||
private Semester semester;
|
||||
private User user;
|
||||
private Subject subjectA;
|
||||
private Subject subjectB;
|
||||
private Professor professor;
|
||||
private Lesson lessonA;
|
||||
private Lesson lessonB;
|
||||
private RegistrationDataset data;
|
||||
|
||||
@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)));
|
||||
data = fixture.registrationDataset();
|
||||
}
|
||||
|
||||
@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);
|
||||
@DisplayName("신청 성공 → 유효 신청 1건")
|
||||
void register() {
|
||||
Scenario.given(data)
|
||||
.when(current -> service.register(
|
||||
current.student().getId(),
|
||||
new CourseRegistrationRequest(current.lesson().getId())))
|
||||
.then(response -> {
|
||||
assertThat(response.totalCredits()).isEqualTo(3);
|
||||
assertThat(response.registeredAt()).isEqualTo(TestData.NOW);
|
||||
assertThat(registrations.countByLesson_IdAndCanceledAtIsNull(data.lesson().getId()))
|
||||
.isEqualTo(1);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void duplicateRegistrationIsRejected() {
|
||||
service.register(user.getId(), new CourseRegistrationRequest(lessonA.getId()));
|
||||
@DisplayName("같은 강의 재신청 → ALREADY_REGISTERED")
|
||||
void duplicate() {
|
||||
service.register(data.student().getId(), new CourseRegistrationRequest(data.lesson().getId()));
|
||||
|
||||
assertThatThrownBy(() -> service.register(user.getId(), new CourseRegistrationRequest(lessonA.getId())))
|
||||
.isInstanceOfSatisfying(RegistrationException.class,
|
||||
ex -> assertThat(ex.getErrorCode()).isEqualTo(RegistrationErrorCode.ALREADY_REGISTERED));
|
||||
Scenario.given(data)
|
||||
.when(current -> service.register(
|
||||
current.student().getId(),
|
||||
new CourseRegistrationRequest(current.lesson().getId())))
|
||||
.thenRejectedWith(REJECTIONS, RegistrationErrorCode.ALREADY_REGISTERED);
|
||||
}
|
||||
|
||||
@Test
|
||||
void cancelThenReregisterKeepsHistoryAndOneActiveRow() {
|
||||
CourseRegistrationResponse first = service.register(user.getId(), new CourseRegistrationRequest(lessonA.getId()));
|
||||
service.cancel(user.getId(), first.registrationId());
|
||||
@DisplayName("취소 후 재신청 → 이력 2건, 유효 1건")
|
||||
void cancelAndRegisterAgain() {
|
||||
CourseRegistrationResponse first = service.register(
|
||||
data.student().getId(),
|
||||
new CourseRegistrationRequest(data.lesson().getId()));
|
||||
service.cancel(data.student().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);
|
||||
Scenario.given(data)
|
||||
.when(current -> service.register(
|
||||
current.student().getId(),
|
||||
new CourseRegistrationRequest(current.lesson().getId())))
|
||||
.then(second -> {
|
||||
assertThat(second.registrationId()).isNotEqualTo(first.registrationId());
|
||||
assertThat(registrations.findAll()).hasSize(2);
|
||||
assertThat(registrations.countByLesson_IdAndCanceledAtIsNull(data.lesson().getId()))
|
||||
.isEqualTo(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));
|
||||
@DisplayName("다른 사용자 취소 → REGISTRATION_FORBIDDEN")
|
||||
void cannotCancelOthers() {
|
||||
CourseRegistrationResponse registration = service.register(
|
||||
data.student().getId(),
|
||||
new CourseRegistrationRequest(data.lesson().getId()));
|
||||
User other = fixture.user(DomainFixtures.studentNamed("다른학생", 2));
|
||||
|
||||
assertThatThrownBy(() -> service.cancel(other.getId(), first.registrationId()))
|
||||
.isInstanceOfSatisfying(RegistrationException.class,
|
||||
ex -> assertThat(ex.getErrorCode()).isEqualTo(RegistrationErrorCode.REGISTRATION_FORBIDDEN));
|
||||
Scenario.given(other)
|
||||
.whenRunning(user -> service.cancel(user.getId(), registration.registrationId()))
|
||||
.thenRejectedWith(REJECTIONS, RegistrationErrorCode.REGISTRATION_FORBIDDEN);
|
||||
}
|
||||
|
||||
@Test
|
||||
void cancelingAlreadyCanceledRegistrationIsRejected() {
|
||||
CourseRegistrationResponse first = service.register(user.getId(), new CourseRegistrationRequest(lessonA.getId()));
|
||||
service.cancel(user.getId(), first.registrationId());
|
||||
@DisplayName("취소 재호출 → 멱등 성공")
|
||||
void repeatedCancelIsIdempotent() {
|
||||
CourseRegistrationResponse registration = service.register(
|
||||
data.student().getId(),
|
||||
new CourseRegistrationRequest(data.lesson().getId()));
|
||||
service.cancel(data.student().getId(), registration.registrationId());
|
||||
|
||||
assertThatThrownBy(() -> service.cancel(user.getId(), first.registrationId()))
|
||||
.isInstanceOfSatisfying(RegistrationException.class,
|
||||
ex -> assertThat(ex.getErrorCode()).isEqualTo(RegistrationErrorCode.ALREADY_CANCELED));
|
||||
Scenario.given(data)
|
||||
.whenRunning(current -> service.cancel(
|
||||
current.student().getId(),
|
||||
registration.registrationId()))
|
||||
.then(ignored -> assertThat(
|
||||
registrations.countByLesson_IdAndCanceledAtIsNull(data.lesson().getId()))
|
||||
.isZero());
|
||||
}
|
||||
|
||||
@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));
|
||||
@DisplayName("취소 건 → 신청 목록 제외")
|
||||
void canceledRegistrationIsHidden() {
|
||||
CourseRegistrationResponse registration = service.register(
|
||||
data.student().getId(),
|
||||
new CourseRegistrationRequest(data.lesson().getId()));
|
||||
service.cancel(data.student().getId(), registration.registrationId());
|
||||
|
||||
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);
|
||||
Scenario.given(data)
|
||||
.when(current -> service.getRegistrations(
|
||||
current.student().getId(),
|
||||
current.semester().getId()))
|
||||
.then(result -> {
|
||||
assertThat(result.totalCredits()).isZero();
|
||||
assertThat(result.registrations()).isEmpty();
|
||||
});
|
||||
}
|
||||
|
||||
@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));
|
||||
@DisplayName("취소 후 정원 → 다음 사용자 신청 가능")
|
||||
void cancelFreesCapacity() {
|
||||
Subject subject = fixture.subject(DomainFixtures.subject("CAP"));
|
||||
Lesson capacityOne = fixture.lesson(
|
||||
DomainFixtures.lesson(subject, data.professor(), data.semester(), 1));
|
||||
fixture.schedule(DomainFixtures.schedule(capacityOne, DayOfWeek.WEDNESDAY, 13, 15));
|
||||
User other = fixture.user(DomainFixtures.studentNamed("대기학생", 2));
|
||||
|
||||
assertThatThrownBy(() -> service.cancel(user.getId(), closedRegistration.getId()))
|
||||
.isInstanceOfSatisfying(RegistrationException.class,
|
||||
ex -> assertThat(ex.getErrorCode()).isEqualTo(RegistrationErrorCode.REGISTRATION_PERIOD_CLOSED));
|
||||
CourseRegistrationResponse first = service.register(
|
||||
data.student().getId(),
|
||||
new CourseRegistrationRequest(capacityOne.getId()));
|
||||
service.cancel(data.student().getId(), first.registrationId());
|
||||
|
||||
assertThat(userLessonRepository.findById(registration.registrationId())).isPresent();
|
||||
Scenario.given(other)
|
||||
.when(user -> service.register(
|
||||
user.getId(),
|
||||
new CourseRegistrationRequest(capacityOne.getId())))
|
||||
.thenAccepted();
|
||||
}
|
||||
|
||||
@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()));
|
||||
@DisplayName("다른 학기 신청 → 현재 학기 학점 계산 제외")
|
||||
void creditsAreScopedBySemester() {
|
||||
Semester otherSemester = fixture.semester(DomainFixtures.semester(
|
||||
null,
|
||||
"2027-1",
|
||||
TestData.TODAY.plusDays(120),
|
||||
TestData.TODAY.plusDays(240),
|
||||
-3600,
|
||||
3600,
|
||||
18));
|
||||
Subject otherSubject = fixture.subject(DomainFixtures.subject("OLD"));
|
||||
Lesson otherLesson = fixture.lesson(
|
||||
DomainFixtures.lesson(otherSubject, data.professor(), otherSemester));
|
||||
fixture.schedule(DomainFixtures.schedule(otherLesson, DayOfWeek.FRIDAY, 9, 11));
|
||||
fixture.registration(DomainFixtures.registration(data.student(), otherLesson));
|
||||
|
||||
var response = service.getRegistrations(user.getId(), semester.getId());
|
||||
Scenario.given(data)
|
||||
.when(current -> service.register(
|
||||
current.student().getId(),
|
||||
new CourseRegistrationRequest(current.lesson().getId())))
|
||||
.then(response -> assertThat(response.totalCredits()).isEqualTo(3));
|
||||
}
|
||||
|
||||
assertThat(response.totalCredits()).isEqualTo(3);
|
||||
assertThat(response.registrations()).extracting(it -> it.lessonId()).containsExactly(lessonB.getId());
|
||||
@Test
|
||||
@DisplayName("신청 기간 종료 → REGISTRATION_PERIOD_CLOSED")
|
||||
void closedPeriod() {
|
||||
fixture.reset();
|
||||
Semester closed = fixture.semester(DomainFixtures.closedSemester());
|
||||
Professor professor = fixture.professor(DomainFixtures.professor());
|
||||
Subject subject = fixture.subject(DomainFixtures.subject("CLOSED"));
|
||||
User student = fixture.user(DomainFixtures.student(2));
|
||||
Lesson lesson = fixture.lesson(DomainFixtures.lesson(subject, professor, closed));
|
||||
fixture.schedule(DomainFixtures.schedule(lesson, DayOfWeek.MONDAY, 9, 11));
|
||||
|
||||
Scenario.given(student)
|
||||
.when(user -> service.register(
|
||||
user.getId(),
|
||||
new CourseRegistrationRequest(lesson.getId())))
|
||||
.thenRejectedWith(REJECTIONS, RegistrationErrorCode.REGISTRATION_PERIOD_CLOSED);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("유효 신청 조회 → DTO 전체 매핑")
|
||||
void activeRegistrationList() {
|
||||
service.register(data.student().getId(), new CourseRegistrationRequest(data.lesson().getId()));
|
||||
|
||||
Scenario.given(data)
|
||||
.when(current -> service.getRegistrations(
|
||||
current.student().getId(),
|
||||
current.semester().getId()))
|
||||
.then(result -> {
|
||||
assertThat(result.totalCredits()).isEqualTo(3);
|
||||
assertThat(result.registrations()).singleElement().satisfies(item -> {
|
||||
assertThat(item.lessonId()).isEqualTo(data.lesson().getId());
|
||||
assertThat(item.subjectCode()).isEqualTo(data.subject().getCode());
|
||||
assertThat(item.subjectName()).isEqualTo(data.subject().getName());
|
||||
assertThat(item.credit()).isEqualTo(3);
|
||||
assertThat(item.professorName()).isEqualTo(data.professor().getName());
|
||||
assertThat(item.schedules()).hasSize(1);
|
||||
assertThat(item.registeredAt()).isEqualTo(TestData.NOW);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("없는 사용자 신청 조회 → USER_NOT_FOUND")
|
||||
void registrationListUserNotFound() {
|
||||
Scenario.given("missing")
|
||||
.when(userId -> service.getRegistrations(userId, data.semester().getId()))
|
||||
.thenRejectedWith(REJECTIONS, RegistrationErrorCode.USER_NOT_FOUND);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("없는 학기 신청 조회 → SEMESTER_NOT_FOUND")
|
||||
void registrationListExplicitSemesterNotFound() {
|
||||
Scenario.given("missing")
|
||||
.when(semesterId -> service.getRegistrations(data.student().getId(), semesterId))
|
||||
.thenRejectedWith(REJECTIONS, RegistrationErrorCode.SEMESTER_NOT_FOUND);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("신청 기간 없음 + 학기 진행 중 → 학기 날짜 fallback")
|
||||
void registrationListAcademicFallback() {
|
||||
fixture.reset();
|
||||
Semester academic = fixture.semester(DomainFixtures.academicSemester("academic"));
|
||||
User student = fixture.user(DomainFixtures.student(2));
|
||||
|
||||
Scenario.given(student)
|
||||
.when(user -> service.getRegistrations(user.getId(), null))
|
||||
.then(result -> {
|
||||
assertThat(result.semesterId()).isEqualTo(academic.getId());
|
||||
assertThat(result.registrations()).isEmpty();
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("현재 학기 없음 → SEMESTER_NOT_FOUND")
|
||||
void registrationListSemesterNotFound() {
|
||||
fixture.reset();
|
||||
User student = fixture.user(DomainFixtures.student(2));
|
||||
|
||||
Scenario.given(student)
|
||||
.when(user -> service.getRegistrations(user.getId(), null))
|
||||
.thenRejectedWith(REJECTIONS, RegistrationErrorCode.SEMESTER_NOT_FOUND);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Idempotency-Key 101자 → VALIDATION_ERROR")
|
||||
void idempotencyKeyTooLong() {
|
||||
String key = "x".repeat(101);
|
||||
|
||||
Scenario.given(key)
|
||||
.when(value -> service.register(
|
||||
data.student().getId(),
|
||||
new CourseRegistrationRequest(data.lesson().getId()),
|
||||
value))
|
||||
.thenRejectedWith(REJECTIONS, RegistrationErrorCode.VALIDATION_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
+166
-62
@@ -1,96 +1,200 @@
|
||||
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.hibernate.SessionFactory;
|
||||
import org.hibernate.stat.Statistics;
|
||||
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.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
|
||||
import com.study.course_registration.dto.lesson.LessonDetailResponse;
|
||||
import com.study.course_registration.dto.lesson.LessonListResponse;
|
||||
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.*;
|
||||
import com.study.course_registration.support.PostgresIntegrationTest;
|
||||
import com.study.course_registration.support.Rejections;
|
||||
import com.study.course_registration.support.Scenario;
|
||||
import com.study.course_registration.support.fixture.DatabaseFixture;
|
||||
import com.study.course_registration.support.fixture.DatabaseFixture.RegistrationDataset;
|
||||
import com.study.course_registration.support.fixture.DomainFixtures;
|
||||
|
||||
@SpringBootTest
|
||||
@ActiveProfiles("test")
|
||||
class LessonQueryServiceIntegrationTest {
|
||||
@Autowired LessonQueryService lessonQueryService;
|
||||
import jakarta.persistence.EntityManagerFactory;
|
||||
|
||||
class LessonQueryServiceIntegrationTest extends PostgresIntegrationTest {
|
||||
private static final Rejections<RegistrationException, RegistrationErrorCode> REJECTIONS =
|
||||
Rejections.of(RegistrationException.class, RegistrationException::getErrorCode);
|
||||
|
||||
@Autowired LessonQueryService service;
|
||||
@Autowired CourseRegistrationService registrationService;
|
||||
@Autowired UserLessonRepository userLessonRepository;
|
||||
@Autowired LessonScheduleRepository lessonScheduleRepository;
|
||||
@Autowired LessonRepository lessonRepository;
|
||||
@Autowired SubjectRepository subjectRepository;
|
||||
@Autowired ProfessorRepository professorRepository;
|
||||
@Autowired SemesterRepository semesterRepository;
|
||||
@Autowired UserRepository userRepository;
|
||||
@Autowired DatabaseFixture fixture;
|
||||
@Autowired EntityManagerFactory entityManagerFactory;
|
||||
|
||||
private Semester semester;
|
||||
private Lesson lesson;
|
||||
private User user;
|
||||
private RegistrationDataset data;
|
||||
|
||||
@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()));
|
||||
data = fixture.registrationDataset();
|
||||
registrationService.register(
|
||||
data.student().getId(),
|
||||
new CourseRegistrationRequest(data.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);
|
||||
});
|
||||
@DisplayName("강의 목록 → 시간표·신청 수 포함")
|
||||
void list() {
|
||||
Scenario.given(data)
|
||||
.when(current -> service.getLessons(current.semester().getId(), null, 0, 20))
|
||||
.then(response -> {
|
||||
assertThat(response.totalElements()).isEqualTo(1);
|
||||
assertThat(response.lessons()).singleElement().satisfies(item -> {
|
||||
assertThat(item.lessonId()).isEqualTo(data.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());
|
||||
@DisplayName("강의 상세 → 과목·학기·신청 수 포함")
|
||||
void detail() {
|
||||
Scenario.given(data.lesson().getId())
|
||||
.when(service::getLesson)
|
||||
.then(response -> {
|
||||
assertThat(response.subjectDescription()).isEqualTo(data.subject().getDescription());
|
||||
assertThat(response.semesterName()).isEqualTo(data.semester().getName());
|
||||
assertThat(response.enrolledCount()).isEqualTo(1);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownSemesterIsRejected() {
|
||||
assertThatThrownBy(() -> lessonQueryService.getLessons("missing", null, 0, 20))
|
||||
.isInstanceOfSatisfying(RegistrationException.class,
|
||||
ex -> assertThat(ex.getErrorCode()).isEqualTo(RegistrationErrorCode.SEMESTER_NOT_FOUND));
|
||||
@DisplayName("없는 학기 → SEMESTER_NOT_FOUND")
|
||||
void unknownSemester() {
|
||||
Scenario.given("missing")
|
||||
.when(id -> service.getLessons(id, null, 0, 20))
|
||||
.thenRejectedWith(REJECTIONS, RegistrationErrorCode.SEMESTER_NOT_FOUND);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("subjectId 필터 → 해당 과목만 조회")
|
||||
void subjectFilter() {
|
||||
Subject other = fixture.subject(DomainFixtures.subject("CS999"));
|
||||
Lesson otherLesson = fixture.lesson(DomainFixtures.lesson(other, data.professor(), data.semester()));
|
||||
fixture.schedule(DomainFixtures.schedule(otherLesson, DayOfWeek.TUESDAY, 9, 11));
|
||||
|
||||
Scenario.given(other.getId())
|
||||
.when(subjectId -> service.getLessons(data.semester().getId(), subjectId, 0, 20))
|
||||
.then(response -> assertThat(response.lessons())
|
||||
.extracting(item -> item.subjectCode())
|
||||
.containsExactly("CS999"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("페이지 크기 1 → 각 페이지 1건")
|
||||
void pagination() {
|
||||
Subject other = fixture.subject(DomainFixtures.subject("CS200"));
|
||||
Lesson otherLesson = fixture.lesson(DomainFixtures.lesson(other, data.professor(), data.semester()));
|
||||
fixture.schedule(DomainFixtures.schedule(otherLesson, DayOfWeek.TUESDAY, 9, 11));
|
||||
|
||||
LessonListResponse first = service.getLessons(data.semester().getId(), null, 0, 1);
|
||||
|
||||
Scenario.given(first)
|
||||
.when(previous -> new PagePair(
|
||||
previous,
|
||||
service.getLessons(data.semester().getId(), null, 1, 1)))
|
||||
.then(pair -> {
|
||||
assertThat(pair.first().lessons()).hasSize(1);
|
||||
assertThat(pair.second().lessons()).hasSize(1);
|
||||
assertThat(pair.first().lessons().getFirst().lessonId())
|
||||
.isNotEqualTo(pair.second().lessons().getFirst().lessonId());
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("학기 시작 전 신청 기간 → 해당 학기 자동 선택")
|
||||
void registrationWindowWinsOverAcademicDate() {
|
||||
fixture.reset();
|
||||
Semester future = fixture.semester(DomainFixtures.futureAcademicSemesterWithOpenRegistration());
|
||||
Professor professor = fixture.professor(DomainFixtures.professor());
|
||||
Subject subject = fixture.subject(DomainFixtures.subject("FUTURE"));
|
||||
Lesson lesson = fixture.lesson(DomainFixtures.lesson(subject, professor, future));
|
||||
fixture.schedule(DomainFixtures.schedule(lesson, DayOfWeek.MONDAY, 9, 11));
|
||||
|
||||
Scenario.given(lesson)
|
||||
.when(ignored -> service.getLessons(null, null, 0, 20))
|
||||
.then(response -> assertThat(response.lessons())
|
||||
.extracting(item -> item.lessonId())
|
||||
.containsExactly(lesson.getId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("강의 6건 조회 → SQL 6회 이하")
|
||||
void bulkQueriesStayBounded() {
|
||||
for (int index = 0; index < 5; index++) {
|
||||
Subject subject = fixture.subject(DomainFixtures.subject("Q" + index));
|
||||
Lesson lesson = fixture.lesson(DomainFixtures.lesson(subject, data.professor(), data.semester()));
|
||||
fixture.schedule(DomainFixtures.schedule(lesson, DayOfWeek.of(index + 1), 13, 15));
|
||||
}
|
||||
Statistics statistics = entityManagerFactory.unwrap(SessionFactory.class).getStatistics();
|
||||
statistics.clear();
|
||||
|
||||
Scenario.given(data)
|
||||
.when(current -> service.getLessons(current.semester().getId(), null, 0, 20))
|
||||
.then(response -> {
|
||||
assertThat(response.lessons()).hasSize(6);
|
||||
assertThat(statistics.getPrepareStatementCount()).isLessThanOrEqualTo(6);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("빈 학기 조회 → 빈 페이지")
|
||||
void emptyPage() {
|
||||
fixture.reset();
|
||||
Semester semester = fixture.semester(DomainFixtures.openSemester());
|
||||
|
||||
Scenario.given(semester.getId())
|
||||
.when(id -> service.getLessons(id, null, 0, 20))
|
||||
.then(result -> {
|
||||
assertThat(result.totalElements()).isZero();
|
||||
assertThat(result.lessons()).isEmpty();
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("신청 기간 없음 + 학기 진행 중 → 학기 날짜 fallback")
|
||||
void academicFallback() {
|
||||
fixture.reset();
|
||||
Semester academic = fixture.semester(DomainFixtures.academicSemester("academic"));
|
||||
Professor professor = fixture.professor(DomainFixtures.professor());
|
||||
Subject subject = fixture.subject(DomainFixtures.subject("ACADEMIC"));
|
||||
Lesson lesson = fixture.lesson(DomainFixtures.lesson(subject, professor, academic));
|
||||
fixture.schedule(DomainFixtures.schedule(lesson, DayOfWeek.MONDAY, 9, 11));
|
||||
|
||||
Scenario.given(lesson)
|
||||
.when(ignored -> service.getLessons(null, null, 0, 20))
|
||||
.then(result -> assertThat(result.lessons())
|
||||
.extracting(item -> item.lessonId())
|
||||
.containsExactly(lesson.getId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("현재 학기 없음 → SEMESTER_NOT_FOUND")
|
||||
void currentSemesterNotFound() {
|
||||
fixture.reset();
|
||||
|
||||
Scenario.given(service)
|
||||
.when(value -> value.getLessons(null, null, 0, 20))
|
||||
.thenRejectedWith(REJECTIONS, RegistrationErrorCode.SEMESTER_NOT_FOUND);
|
||||
}
|
||||
|
||||
private record PagePair(LessonListResponse first, LessonListResponse second) {
|
||||
}
|
||||
}
|
||||
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
package com.study.course_registration.service;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
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 com.study.course_registration.entity.Semester;
|
||||
import com.study.course_registration.enums.RegistrationErrorCode;
|
||||
import com.study.course_registration.exception.RegistrationException;
|
||||
import com.study.course_registration.support.PostgresIntegrationTest;
|
||||
import com.study.course_registration.support.Rejections;
|
||||
import com.study.course_registration.support.Scenario;
|
||||
import com.study.course_registration.support.fixture.DatabaseFixture;
|
||||
import com.study.course_registration.support.fixture.DomainFixtures;
|
||||
|
||||
class SemesterResolverIntegrationTest extends PostgresIntegrationTest {
|
||||
private static final Rejections<RegistrationException, RegistrationErrorCode> REJECTIONS =
|
||||
Rejections.of(RegistrationException.class, RegistrationException::getErrorCode);
|
||||
@Autowired DatabaseFixture fixture;
|
||||
@Autowired SemesterResolver resolver;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
fixture.reset();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("semesterId 명시 → 해당 학기")
|
||||
void explicitSemester() {
|
||||
Semester semester = fixture.semester(DomainFixtures.openSemester());
|
||||
|
||||
Scenario.given(semester.getId())
|
||||
.when(resolver::resolve)
|
||||
.then(result -> assertThat(result.getId()).isEqualTo(semester.getId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("신청 기간 학기 1개 → 해당 학기")
|
||||
void registrationWindow() {
|
||||
Semester semester = fixture.semester(DomainFixtures.futureAcademicSemesterWithOpenRegistration());
|
||||
|
||||
Scenario.given((String) null)
|
||||
.when(resolver::resolve)
|
||||
.then(result -> assertThat(result.getId()).isEqualTo(semester.getId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("신청 기간 학기 2개 → 데이터 오류")
|
||||
void overlappingRegistrationWindows() {
|
||||
fixture.semester(DomainFixtures.openSemester("semester-a", "A", 18));
|
||||
fixture.semester(DomainFixtures.openSemester("semester-b", "B", 18));
|
||||
|
||||
assertThatThrownBy(() -> resolver.resolve(null))
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.hasMessageContaining("두 개 이상의 수강신청 학기");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("활성 학기 없음 → SEMESTER_NOT_FOUND")
|
||||
void notFound() {
|
||||
Scenario.given((String) null)
|
||||
.when(resolver::resolve)
|
||||
.thenRejectedWith(REJECTIONS, RegistrationErrorCode.SEMESTER_NOT_FOUND);
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package com.study.course_registration.service.lock;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.inOrder;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.InOrder;
|
||||
|
||||
import com.study.course_registration.entity.Lesson;
|
||||
import com.study.course_registration.entity.User;
|
||||
import com.study.course_registration.repository.LessonRepository;
|
||||
import com.study.course_registration.repository.UserRepository;
|
||||
import com.study.course_registration.support.fixture.DomainFixtures;
|
||||
|
||||
class RegistrationLockManagerTest {
|
||||
@Test
|
||||
@DisplayName("락 획득 순서 → User 다음 Lesson")
|
||||
void userThenLesson() {
|
||||
UserRepository users = mock(UserRepository.class);
|
||||
LessonRepository lessons = mock(LessonRepository.class);
|
||||
User user = DomainFixtures.student(2);
|
||||
Lesson lesson = DomainFixtures.lesson(DomainFixtures.subject("LOCK"), DomainFixtures.professor(), DomainFixtures.openSemester());
|
||||
when(users.findByIdForUpdate("user")).thenReturn(Optional.of(user));
|
||||
when(lessons.findByIdForUpdate("lesson")).thenReturn(Optional.of(lesson));
|
||||
|
||||
RegistrationLockManager.LockedRegistration result = new RegistrationLockManager(users, lessons).lock("user", "lesson");
|
||||
|
||||
InOrder order = inOrder(users, lessons);
|
||||
order.verify(users).findByIdForUpdate("user");
|
||||
order.verify(lessons).findByIdForUpdate("lesson");
|
||||
assertThat(result.user()).isSameAs(user);
|
||||
assertThat(result.lesson()).isSameAs(lesson);
|
||||
}
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
package com.study.course_registration.service.policy;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThatCode;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
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.Professor;
|
||||
import com.study.course_registration.entity.Semester;
|
||||
import com.study.course_registration.entity.Subject;
|
||||
import com.study.course_registration.support.Scenario;
|
||||
import com.study.course_registration.support.fixture.DomainFixtures;
|
||||
|
||||
@DisplayName("강의 시간표 정책")
|
||||
class LessonSchedulePolicyTest {
|
||||
private final LessonSchedulePolicy policy = new LessonSchedulePolicy(new ScheduleConflictChecker());
|
||||
|
||||
@Test
|
||||
@DisplayName("같은 강의 시간 겹침 → 거부")
|
||||
void overlap() {
|
||||
Semester semester = DomainFixtures.openSemester();
|
||||
Subject subject = DomainFixtures.subject("CS101");
|
||||
Lesson lesson = DomainFixtures.lesson(subject, DomainFixtures.professor(), semester);
|
||||
|
||||
List<LessonSchedule> schedules = List.of(
|
||||
DomainFixtures.schedule(lesson, DayOfWeek.MONDAY, 9, 11),
|
||||
DomainFixtures.schedule(lesson, DayOfWeek.MONDAY, 10, 12));
|
||||
|
||||
assertThatThrownBy(() -> policy.validate(schedules))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("같은 강의 경계 접촉 → 허용")
|
||||
void boundary() {
|
||||
Semester semester = DomainFixtures.openSemester();
|
||||
Subject subject = DomainFixtures.subject("CS101");
|
||||
Lesson lesson = DomainFixtures.lesson(subject, DomainFixtures.professor(), semester);
|
||||
|
||||
List<LessonSchedule> schedules = List.of(
|
||||
DomainFixtures.schedule(lesson, DayOfWeek.MONDAY, 9, 11),
|
||||
DomainFixtures.schedule(lesson, DayOfWeek.MONDAY, 11, 13));
|
||||
|
||||
assertThatCode(() -> policy.validate(schedules)).doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("서로 다른 강의 시간 겹침 → 허용")
|
||||
void differentLessons() {
|
||||
Semester semester = DomainFixtures.openSemester();
|
||||
Professor professor = DomainFixtures.professor();
|
||||
Lesson left = DomainFixtures.lesson(DomainFixtures.subject("CS101"), professor, semester);
|
||||
Lesson right = DomainFixtures.lesson(DomainFixtures.subject("CS102"), professor, semester);
|
||||
|
||||
List<LessonSchedule> schedules = List.of(
|
||||
DomainFixtures.schedule(left, DayOfWeek.MONDAY, 9, 11),
|
||||
DomainFixtures.schedule(right, DayOfWeek.MONDAY, 9, 11));
|
||||
|
||||
Scenario.given(schedules)
|
||||
.whenRunning(policy::validate)
|
||||
.thenAccepted();
|
||||
}
|
||||
}
|
||||
+46
-125
@@ -13,185 +13,106 @@ 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;
|
||||
import com.study.course_registration.support.fixture.DomainFixtures;
|
||||
import com.study.course_registration.support.fixture.TestData;
|
||||
|
||||
/**
|
||||
* 수강신청 도메인의 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 Semester semester = DomainFixtures.openSemester("semester-1", "2026-1", 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 Slot candidateSlot = new Slot(DayOfWeek.MONDAY, 15, 16);
|
||||
private boolean existingIsSameLesson;
|
||||
private String existingSubjectId;
|
||||
private int existingCredit = 3;
|
||||
private Slot existingSlot;
|
||||
|
||||
private Slot existingSlot = new Slot(DayOfWeek.TUESDAY, 15, 16);
|
||||
private long enrolledCount = 1;
|
||||
|
||||
private RegistrationFixture(long grade) {
|
||||
this.grade = grade;
|
||||
}
|
||||
private RegistrationFixture(long grade) { this.grade = grade; }
|
||||
|
||||
/** given: N학년 학부생. 모든 시나리오의 시작점이다. */
|
||||
static RegistrationFixture student(long grade) {
|
||||
return new RegistrationFixture(grade);
|
||||
}
|
||||
static RegistrationFixture student(long grade) { return new RegistrationFixture(grade); }
|
||||
RegistrationFixture semesterWithMaxCredits(int maxCredits) { semester = DomainFixtures.openSemester("semester-1", "2026-1", maxCredits); return this; }
|
||||
RegistrationFixture inClosedSemester() { semester = DomainFixtures.closedSemester("semester-closed", "closed"); return this; }
|
||||
RegistrationFixture applyingFor(String subjectId, int credit) { candidateSubjectId = subjectId; candidateCredit = credit; return this; }
|
||||
RegistrationFixture requiringMinGrade(long value) { minGrade = value; return this; }
|
||||
RegistrationFixture requiringRole(UserRole role) { allowedRole = role; return this; }
|
||||
RegistrationFixture withCapacity(int value) { capacity = value; return this; }
|
||||
RegistrationFixture alreadyEnrolled(long value) { enrolledCount = value; return this; }
|
||||
RegistrationFixture scheduledOn(DayOfWeek day, int start, int end) { candidateSlot = new Slot(day, start, end); return this; }
|
||||
RegistrationFixture withoutSchedule() { candidateSlot = null; return this; }
|
||||
RegistrationFixture alreadyRegisteredSameLesson() { existingIsSameLesson = true; return this; }
|
||||
RegistrationFixture alreadyRegistered(String subjectId, int credit) { existingSubjectId = subjectId; existingCredit = credit; return this; }
|
||||
RegistrationFixture alreadyRegisteredOn(DayOfWeek day, int start, int end) { existingSlot = new Slot(day, start, end); return this; }
|
||||
RegistrationFixture existingWithoutSchedule() { existingSlot = null; return this; }
|
||||
|
||||
/** given: 학점 상한이 N인 학기 (기본 18) */
|
||||
RegistrationFixture semesterWithMaxCredits(int maxCredits) {
|
||||
this.semester = TestFixtures.semester(maxCredits);
|
||||
return this;
|
||||
}
|
||||
RegistrationFixture checkEligibility() { return checkEligibilityAt(TestData.NOW); }
|
||||
|
||||
/** 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);
|
||||
validator.validateLocked(fixture.candidate(), fixture.existingRegistrations(), fixture.schedules(), enrolledCount);
|
||||
return this;
|
||||
}
|
||||
|
||||
RegistrationFixture attempt() {
|
||||
checkEligibility();
|
||||
register();
|
||||
return this;
|
||||
}
|
||||
|
||||
/** 신청이 성사됐을 때의 누적 학점 */
|
||||
int totalCreditsAfter() {
|
||||
Fixture fixture = assemble();
|
||||
return validator.totalCreditsAfter(fixture.candidate(), fixture.existingRegistrations());
|
||||
}
|
||||
|
||||
Instant registrationEndAt() {
|
||||
return semester.getRegistrationEndAt();
|
||||
}
|
||||
Instant registrationStartAt() { return semester.getRegistrationStartAt(); }
|
||||
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<>();
|
||||
User user = DomainFixtures.student("user", grade);
|
||||
Lesson candidate = DomainFixtures.lesson(CANDIDATE_LESSON_ID, CANDIDATE_LESSON_ID,
|
||||
DomainFixtures.subject(candidateSubjectId, candidateSubjectId, candidateCredit),
|
||||
DomainFixtures.professor("prof-" + CANDIDATE_LESSON_ID),
|
||||
semester, capacity, minGrade, allowedRole);
|
||||
List<UserLesson> existing = 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));
|
||||
existing.add(DomainFixtures.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));
|
||||
Lesson existingLesson = DomainFixtures.lesson(EXISTING_LESSON_ID, EXISTING_LESSON_ID,
|
||||
DomainFixtures.subject(existingSubjectId, existingSubjectId, existingCredit),
|
||||
DomainFixtures.professor("prof-" + EXISTING_LESSON_ID),
|
||||
semester, 30, null, null);
|
||||
existing.add(DomainFixtures.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);
|
||||
return new Fixture(user, candidate, existing, schedules);
|
||||
}
|
||||
|
||||
private record Slot(DayOfWeek day, int startHour, int endHour) {
|
||||
LessonSchedule toSchedule(String id, Lesson lesson) {
|
||||
return TestFixtures.schedule(id, lesson, day, startHour, endHour);
|
||||
return DomainFixtures.schedule(id, lesson, day, startHour, endHour);
|
||||
}
|
||||
}
|
||||
|
||||
private record Fixture(User user,
|
||||
Lesson candidate,
|
||||
List<UserLesson> existingRegistrations,
|
||||
Map<String, List<LessonSchedule>> schedules) {
|
||||
}
|
||||
private record Fixture(User user, Lesson candidate, List<UserLesson> existingRegistrations,
|
||||
Map<String, List<LessonSchedule>> schedules) {}
|
||||
}
|
||||
|
||||
+119
-105
@@ -16,155 +16,169 @@ 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)")
|
||||
@DisplayName("수강신청 정책")
|
||||
class RegistrationValidatorTest {
|
||||
|
||||
/** 이 도메인이 거부하는 방식. then이 도메인을 아는 지점은 여기 한 곳뿐이다. */
|
||||
private static final Rejections<RegistrationException, RegistrationErrorCode> REJECTIONS =
|
||||
Rejections.of(RegistrationException.class, RegistrationException::getErrorCode);
|
||||
|
||||
@Nested
|
||||
@DisplayName("R1 신청 기간 — 기간 밖이면 REGISTRATION_PERIOD_CLOSED")
|
||||
class RegistrationPeriod {
|
||||
@DisplayName("R1 신청 기간")
|
||||
class Period {
|
||||
@Test
|
||||
@DisplayName("신청 종료 시각 정각에 신청하면 통과한다 (종료 시각은 기간에 포함된다)")
|
||||
void endAtIsInclusive() {
|
||||
RegistrationFixture fixture = RegistrationFixture.student(1);
|
||||
|
||||
Scenario.given(fixture)
|
||||
.when(f -> f.checkEligibilityAt(fixture.registrationEndAt()))
|
||||
.thenAccepted();
|
||||
@DisplayName("시작 정각 → 허용")
|
||||
void startInclusive() {
|
||||
RegistrationFixture fixture = RegistrationFixture.student(2);
|
||||
Scenario.given(fixture).when(f -> f.checkEligibilityAt(f.registrationStartAt())).thenAccepted();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("기간이 지났으면 학년·역할 조건도 함께 어겨도 기간 오류를 먼저 반환한다")
|
||||
void closedPeriodIsCheckedBeforeEligibility() {
|
||||
Scenario.given(RegistrationFixture.student(1)
|
||||
.inClosedSemester()
|
||||
.requiringMinGrade(3)
|
||||
.requiringRole(UserRole.POSTGRADUATE))
|
||||
.when(RegistrationFixture::checkEligibility)
|
||||
@DisplayName("종료 정각 → 허용")
|
||||
void endInclusive() {
|
||||
RegistrationFixture fixture = RegistrationFixture.student(2);
|
||||
Scenario.given(fixture).when(f -> f.checkEligibilityAt(f.registrationEndAt())).thenAccepted();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("기간 종료 + 학년 미달 → R1")
|
||||
void periodBeforeGrade() {
|
||||
Scenario.given(RegistrationFixture.student(1).inClosedSemester().requiringMinGrade(3))
|
||||
.when(RegistrationFixture::attempt)
|
||||
.thenRejectedWith(REJECTIONS, RegistrationErrorCode.REGISTRATION_PERIOD_CLOSED);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("R2 학년 제한 — 미달이면 NOT_ELIGIBLE_GRADE")
|
||||
class MinGrade {
|
||||
@DisplayName("R2~R5 자격·중복")
|
||||
class EligibilityAndDuplicate {
|
||||
@Test
|
||||
@DisplayName("1학년이 3학년 이상 강의를 신청하면 거부한다")
|
||||
void rejectsGradeBelowMinimum() {
|
||||
Scenario.given(RegistrationFixture.student(1)
|
||||
.requiringMinGrade(3))
|
||||
.when(RegistrationFixture::checkEligibility)
|
||||
@DisplayName("학년 미달 + 역할 불일치 → R2")
|
||||
void gradeBeforeRole() {
|
||||
Scenario.given(RegistrationFixture.student(1).requiringMinGrade(3).requiringRole(UserRole.POSTGRADUATE))
|
||||
.when(RegistrationFixture::attempt)
|
||||
.thenRejectedWith(REJECTIONS, RegistrationErrorCode.NOT_ELIGIBLE_GRADE);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("R3 역할 제한 — 불일치하면 NOT_ELIGIBLE_ROLE")
|
||||
class AllowedRole {
|
||||
@Test
|
||||
@DisplayName("학부생이 대학원생 전용 강의를 신청하면 거부한다")
|
||||
void rejectsRoleMismatch() {
|
||||
Scenario.given(RegistrationFixture.student(3)
|
||||
.requiringRole(UserRole.POSTGRADUATE))
|
||||
.when(RegistrationFixture::checkEligibility)
|
||||
@DisplayName("역할 불일치 + 같은 강의 → R3")
|
||||
void roleBeforeDuplicate() {
|
||||
Scenario.given(RegistrationFixture.student(3).requiringRole(UserRole.POSTGRADUATE).alreadyRegisteredSameLesson())
|
||||
.when(RegistrationFixture::attempt)
|
||||
.thenRejectedWith(REJECTIONS, RegistrationErrorCode.NOT_ELIGIBLE_ROLE);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("R4·R5 중복 신청 — 같은 분반이면 ALREADY_REGISTERED, 다른 분반이면 DUPLICATE_SUBJECT")
|
||||
class Duplicate {
|
||||
@Test
|
||||
@DisplayName("이미 신청한 그 강의를 다시 신청하면 과목 중복보다 강의 중복을 먼저 반환한다")
|
||||
void sameLessonTakesPrecedenceOverSameSubject() {
|
||||
Scenario.given(RegistrationFixture.student(2)
|
||||
.alreadyRegisteredSameLesson())
|
||||
.when(RegistrationFixture::register)
|
||||
@DisplayName("같은 강의 → R4")
|
||||
void duplicateLesson() {
|
||||
Scenario.given(RegistrationFixture.student(2).alreadyRegisteredSameLesson())
|
||||
.when(RegistrationFixture::attempt)
|
||||
.thenRejectedWith(REJECTIONS, RegistrationErrorCode.ALREADY_REGISTERED);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("같은 과목의 다른 분반을 신청하면 거부한다")
|
||||
void rejectsDifferentSectionOfSameSubject() {
|
||||
@DisplayName("같은 과목 다른 분반 → R5")
|
||||
void duplicateSubject() {
|
||||
Scenario.given(RegistrationFixture.student(2).applyingFor("subject", 3).alreadyRegistered("subject", 3))
|
||||
.when(RegistrationFixture::attempt)
|
||||
.thenRejectedWith(REJECTIONS, RegistrationErrorCode.DUPLICATE_SUBJECT);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("과목 중복 + 시간 충돌 → R5")
|
||||
void duplicateSubjectBeforeSchedule() {
|
||||
Scenario.given(RegistrationFixture.student(2)
|
||||
.applyingFor("subject", 3)
|
||||
.alreadyRegistered("subject", 3))
|
||||
.when(RegistrationFixture::register)
|
||||
.applyingFor("same", 3).scheduledOn(DayOfWeek.MONDAY, 10, 12)
|
||||
.alreadyRegistered("same", 3).alreadyRegisteredOn(DayOfWeek.MONDAY, 9, 11))
|
||||
.when(RegistrationFixture::attempt)
|
||||
.thenRejectedWith(REJECTIONS, RegistrationErrorCode.DUPLICATE_SUBJECT);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("R6 시간표 충돌 — 겹치면 SCHEDULE_CONFLICT")
|
||||
class ScheduleConflict {
|
||||
@ParameterizedTest(name = "[{index}] {5}")
|
||||
@DisplayName("R6 시간표")
|
||||
class Schedule {
|
||||
@ParameterizedTest(name = "{4}")
|
||||
@CsvSource(textBlock = """
|
||||
# 기존 수업 시작, 끝 | 신청 수업 시작, 끝 | 기대 에러(비우면 통과) | 설명
|
||||
9, 11, 10, 12, SCHEDULE_CONFLICT, '기존 수업과 시간이 겹치면 거부한다 (월 9-11 vs 월 10-12)'
|
||||
9, 11, 11, 13, , '앞 수업이 끝나는 시각에 시작하면 신청할 수 있다 (월 9-11 vs 월 11-13)'
|
||||
9, 11, 10, 12, '겹침 → R6'
|
||||
9, 11, 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);
|
||||
}
|
||||
}
|
||||
|
||||
@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) {
|
||||
void overlap(int oldStart, int oldEnd, int newStart, int newEnd, String name) {
|
||||
RegistrationFixture fixture = RegistrationFixture.student(2)
|
||||
.semesterWithMaxCredits(maxCredits)
|
||||
.alreadyRegistered("subject-a", existingCredit)
|
||||
.applyingFor("subject-b", newCredit);
|
||||
.alreadyRegistered("old", 3).alreadyRegisteredOn(DayOfWeek.MONDAY, oldStart, oldEnd)
|
||||
.applyingFor("new", 3).scheduledOn(DayOfWeek.MONDAY, newStart, newEnd);
|
||||
|
||||
Scenario.given(fixture)
|
||||
.when(RegistrationFixture::register)
|
||||
.then(REJECTIONS, expected);
|
||||
if (newStart < oldEnd) {
|
||||
Scenario.given(fixture).when(RegistrationFixture::attempt)
|
||||
.thenRejectedWith(REJECTIONS, RegistrationErrorCode.SCHEDULE_CONFLICT);
|
||||
} else {
|
||||
Scenario.given(fixture).when(RegistrationFixture::attempt).thenAccepted();
|
||||
}
|
||||
}
|
||||
|
||||
assertThat(fixture.totalCreditsAfter())
|
||||
.as("신청 후 누적 학점")
|
||||
.isEqualTo(existingCredit + newCredit);
|
||||
@Test
|
||||
@DisplayName("시간 충돌 + 학점 초과 → R6")
|
||||
void scheduleBeforeCredit() {
|
||||
Scenario.given(RegistrationFixture.student(2).semesterWithMaxCredits(5)
|
||||
.alreadyRegistered("old", 3).alreadyRegisteredOn(DayOfWeek.MONDAY, 9, 11)
|
||||
.applyingFor("new", 3).scheduledOn(DayOfWeek.MONDAY, 10, 12))
|
||||
.when(RegistrationFixture::attempt)
|
||||
.thenRejectedWith(REJECTIONS, RegistrationErrorCode.SCHEDULE_CONFLICT);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("신청 강의 시간표 없음 → 500")
|
||||
void missingCandidateSchedule() {
|
||||
Scenario.given(RegistrationFixture.student(2).withoutSchedule())
|
||||
.when(RegistrationFixture::attempt)
|
||||
.thenRejectedWith(REJECTIONS, RegistrationErrorCode.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("기존 강의 시간표 없음 → 500")
|
||||
void missingExistingSchedule() {
|
||||
Scenario.given(RegistrationFixture.student(2).alreadyRegistered("old", 3).existingWithoutSchedule())
|
||||
.when(RegistrationFixture::attempt)
|
||||
.thenRejectedWith(REJECTIONS, RegistrationErrorCode.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("R8 정원 — 가득 차면 CAPACITY_EXCEEDED")
|
||||
class Capacity {
|
||||
@ParameterizedTest(name = "[{index}] {3}")
|
||||
@DisplayName("R7 학점")
|
||||
class Credit {
|
||||
@ParameterizedTest(name = "{4}")
|
||||
@CsvSource(textBlock = """
|
||||
# 정원 | 현재 유효 신청 수 | 기대 에러(비우면 통과) | 설명
|
||||
30, 29, , '마지막 한 자리는 신청할 수 있다 (29/30)'
|
||||
30, 30, CAPACITY_EXCEEDED , '정원이 가득 차면 거부한다 (30/30)'
|
||||
6, 3, 3, , '3+3=6 → 허용'
|
||||
5, 3, 3, CREDIT_LIMIT_EXCEEDED, '3+3>5 → R7'
|
||||
""")
|
||||
void capacity(int capacity, long enrolledCount,
|
||||
RegistrationErrorCode expected, String description) {
|
||||
Scenario.given(RegistrationFixture.student(2)
|
||||
.withCapacity(capacity)
|
||||
.alreadyEnrolled(enrolledCount))
|
||||
.when(RegistrationFixture::register)
|
||||
void limit(int max, int oldCredit, int newCredit, RegistrationErrorCode expected, String name) {
|
||||
RegistrationFixture fixture = RegistrationFixture.student(2).semesterWithMaxCredits(max)
|
||||
.alreadyRegistered("old", oldCredit).applyingFor("new", newCredit);
|
||||
|
||||
Scenario.given(fixture).when(RegistrationFixture::attempt).then(REJECTIONS, expected);
|
||||
assertThat(fixture.totalCreditsAfter()).isEqualTo(oldCredit + newCredit);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("학점 초과 + 정원 초과 → R7")
|
||||
void creditBeforeCapacity() {
|
||||
Scenario.given(RegistrationFixture.student(2).semesterWithMaxCredits(5)
|
||||
.alreadyRegistered("old", 3).applyingFor("new", 3)
|
||||
.withCapacity(30).alreadyEnrolled(30))
|
||||
.when(RegistrationFixture::attempt)
|
||||
.thenRejectedWith(REJECTIONS, RegistrationErrorCode.CREDIT_LIMIT_EXCEEDED);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("R8 정원")
|
||||
class Capacity {
|
||||
@ParameterizedTest(name = "{3}")
|
||||
@CsvSource(textBlock = """
|
||||
30, 29, , '29/30 → 허용'
|
||||
30, 30, CAPACITY_EXCEEDED, '30/30 → R8'
|
||||
""")
|
||||
void capacity(int capacity, long enrolled, RegistrationErrorCode expected, String name) {
|
||||
Scenario.given(RegistrationFixture.student(2).withCapacity(capacity).alreadyEnrolled(enrolled))
|
||||
.when(RegistrationFixture::attempt)
|
||||
.then(REJECTIONS, expected);
|
||||
}
|
||||
}
|
||||
|
||||
+13
-17
@@ -9,29 +9,25 @@ import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
|
||||
import com.study.course_registration.entity.LessonSchedule;
|
||||
import com.study.course_registration.support.fixture.DomainFixtures;
|
||||
|
||||
@DisplayName("R6 시간 블록 겹침 판정 (Requirements.md 4.3)")
|
||||
@DisplayName("시간표 겹침")
|
||||
class ScheduleConflictCheckerTest {
|
||||
private final ScheduleConflictChecker checker = new ScheduleConflictChecker();
|
||||
|
||||
@DisplayName("두 시간 블록이 겹치는지 판정한다")
|
||||
@ParameterizedTest(name = "[{index}] {7}")
|
||||
@ParameterizedTest(name = "{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, '시간이 같아도 요일이 다르면 충돌이 아니다'
|
||||
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);
|
||||
void overlaps(DayOfWeek dayA, int startA, int endA, DayOfWeek dayB, int startB, int endB,
|
||||
boolean expected, String name) {
|
||||
LessonSchedule a = DomainFixtures.schedule(dayA, startA, endA);
|
||||
LessonSchedule b = DomainFixtures.schedule(dayB, startB, endB);
|
||||
|
||||
// when & then
|
||||
assertThat(checker.overlaps(a, b)).as(description).isEqualTo(expected);
|
||||
assertThat(checker.overlaps(b, a)).as(description + " (순서를 바꿔도 같다)").isEqualTo(expected);
|
||||
assertThat(checker.overlaps(a, b)).isEqualTo(expected);
|
||||
assertThat(checker.overlaps(b, a)).isEqualTo(expected);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,63 +0,0 @@
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.study.course_registration.support;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Inherited;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.context.annotation.Import;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
|
||||
import com.study.course_registration.support.fixture.TestFixtureConfig;
|
||||
|
||||
@Inherited
|
||||
@Target(ElementType.TYPE)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@SpringBootTest
|
||||
@ActiveProfiles("test")
|
||||
@Import(TestFixtureConfig.class)
|
||||
public @interface CourseIntegrationTest {
|
||||
}
|
||||
@@ -2,13 +2,8 @@ package com.study.course_registration.support;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* then 단계. when의 실행 결과는 값을 돌려줬거나 예외로 거부됐거나 둘 중 하나다.
|
||||
*
|
||||
* <p>도메인 타입을 모른다. 예외 타입과 코드 추출 방식은 {@link Rejections}로 받는다.
|
||||
*
|
||||
* @param <R> when이 돌려준 값의 타입
|
||||
*/
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public final class Outcome<R> {
|
||||
private final R result;
|
||||
private final RuntimeException thrown;
|
||||
@@ -18,38 +13,34 @@ public final class Outcome<R> {
|
||||
this.thrown = thrown;
|
||||
}
|
||||
|
||||
/** then: 거부되지 않아야 한다. 돌려준 값을 그대로 넘겨주므로 이어서 내용을 확인할 수 있다. */
|
||||
public R thenAccepted() {
|
||||
if (thrown != null) {
|
||||
throw new AssertionError("통과해야 하는데 " + thrown.getClass().getSimpleName()
|
||||
+ " 이(가) 발생했다: " + thrown.getMessage(), thrown);
|
||||
throw new AssertionError(
|
||||
"성공해야 하지만 " + thrown.getClass().getSimpleName() + " 발생: " + thrown.getMessage(),
|
||||
thrown);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* then: {@code expected}가 null이면 통과, 값이 있으면 그 코드로 거부되어야 한다.
|
||||
*
|
||||
* <p>표 기반 테스트에서 "기대 에러 칸이 비어 있으면 통과"를 그대로 표현하기 위한 형태다.
|
||||
*/
|
||||
public void then(Consumer<R> assertions) {
|
||||
assertions.accept(thenAccepted());
|
||||
}
|
||||
|
||||
public void thenAccepted(Consumer<R> assertions) {
|
||||
then(assertions);
|
||||
}
|
||||
|
||||
public <X extends RuntimeException, E> void then(Rejections<X, E> rejections, E expected) {
|
||||
if (expected == null) {
|
||||
thenAccepted();
|
||||
} else {
|
||||
thenRejectedWith(rejections, expected);
|
||||
return;
|
||||
}
|
||||
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);
|
||||
assertThat(thrown).as("예외가 발생해야 한다").isNotNull();
|
||||
assertThat(thrown).isInstanceOf(rejections.type());
|
||||
assertThat(rejections.codeOf(thrown)).isEqualTo(expected);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.study.course_registration.support;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
|
||||
public final class PessimisticLockProbe {
|
||||
private PessimisticLockProbe() {}
|
||||
|
||||
public static void assertSecondTransactionBlocks(
|
||||
PlatformTransactionManager transactionManager,
|
||||
Supplier<?> firstLock,
|
||||
Supplier<?> secondLock) throws Exception {
|
||||
ExecutorService executor = Executors.newFixedThreadPool(2);
|
||||
CountDownLatch firstLocked = new CountDownLatch(1);
|
||||
CountDownLatch releaseFirst = new CountDownLatch(1);
|
||||
TransactionTemplate transaction = new TransactionTemplate(transactionManager);
|
||||
|
||||
try {
|
||||
Future<?> first = executor.submit(() -> transaction.executeWithoutResult(status -> {
|
||||
firstLock.get();
|
||||
firstLocked.countDown();
|
||||
await(releaseFirst);
|
||||
}));
|
||||
|
||||
assertThat(firstLocked.await(5, TimeUnit.SECONDS)).isTrue();
|
||||
|
||||
Future<?> second = executor.submit(() -> transaction.executeWithoutResult(status -> secondLock.get()));
|
||||
|
||||
assertThatThrownBy(() -> second.get(250, TimeUnit.MILLISECONDS))
|
||||
.isInstanceOf(TimeoutException.class);
|
||||
|
||||
releaseFirst.countDown();
|
||||
first.get(5, TimeUnit.SECONDS);
|
||||
second.get(5, TimeUnit.SECONDS);
|
||||
} finally {
|
||||
releaseFirst.countDown();
|
||||
executor.shutdownNow();
|
||||
executor.awaitTermination(5, TimeUnit.SECONDS);
|
||||
}
|
||||
}
|
||||
|
||||
private static void await(CountDownLatch latch) {
|
||||
try {
|
||||
if (!latch.await(5, TimeUnit.SECONDS)) {
|
||||
throw new AssertionError("락 테스트 release 신호를 받지 못했습니다.");
|
||||
}
|
||||
} catch (InterruptedException interrupted) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new AssertionError("락 테스트가 중단되었습니다.", interrupted);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.study.course_registration.support;
|
||||
|
||||
import org.springframework.test.context.DynamicPropertyRegistry;
|
||||
import org.springframework.test.context.DynamicPropertySource;
|
||||
import org.testcontainers.postgresql.PostgreSQLContainer;
|
||||
import org.testcontainers.junit.jupiter.Testcontainers;
|
||||
import org.testcontainers.utility.DockerImageName;
|
||||
|
||||
@CourseIntegrationTest
|
||||
@Testcontainers
|
||||
public abstract class PostgresIntegrationTest {
|
||||
private static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer(DockerImageName.parse("postgres:16-alpine"));
|
||||
|
||||
static {
|
||||
POSTGRES.start();
|
||||
}
|
||||
|
||||
@DynamicPropertySource
|
||||
static void postgres(DynamicPropertyRegistry registry) {
|
||||
registry.add("spring.datasource.url", POSTGRES::getJdbcUrl);
|
||||
registry.add("spring.datasource.username", POSTGRES::getUsername);
|
||||
registry.add("spring.datasource.password", POSTGRES::getPassword);
|
||||
registry.add("spring.flyway.locations", () -> "classpath:db/migration/postgresql");
|
||||
registry.add("spring.datasource.hikari.connection-init-sql", () -> "SET lock_timeout TO '3s'");
|
||||
}
|
||||
}
|
||||
@@ -2,20 +2,6 @@ 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;
|
||||
@@ -29,11 +15,6 @@ public final class Rejections<X extends RuntimeException, E> {
|
||||
return new Rejections<>(type, codeOf);
|
||||
}
|
||||
|
||||
Class<X> type() {
|
||||
return type;
|
||||
}
|
||||
|
||||
E codeOf(Throwable thrown) {
|
||||
return codeOf.apply(type.cast(thrown));
|
||||
}
|
||||
Class<X> type() { return type; }
|
||||
E codeOf(Throwable thrown) { return codeOf.apply(type.cast(thrown)); }
|
||||
}
|
||||
|
||||
@@ -1,24 +1,8 @@
|
||||
package com.study.course_registration.support;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
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;
|
||||
|
||||
@@ -26,17 +10,10 @@ public final class Scenario<T> {
|
||||
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);
|
||||
@@ -44,4 +21,13 @@ public final class Scenario<T> {
|
||||
return new Outcome<>(null, thrown);
|
||||
}
|
||||
}
|
||||
|
||||
public Outcome<Void> whenRunning(Consumer<T> action) {
|
||||
try {
|
||||
action.accept(fixture);
|
||||
return new Outcome<>(null, null);
|
||||
} catch (RuntimeException thrown) {
|
||||
return new Outcome<>(null, thrown);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
package com.study.course_registration.support.fixture;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
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;
|
||||
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.RegistrationIdempotencyRepository;
|
||||
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;
|
||||
|
||||
public final class DatabaseFixture {
|
||||
private final RegistrationIdempotencyRepository idempotencies;
|
||||
private final UserLessonRepository registrations;
|
||||
private final LessonScheduleRepository schedules;
|
||||
private final LessonRepository lessons;
|
||||
private final SubjectRepository subjects;
|
||||
private final ProfessorRepository professors;
|
||||
private final SemesterRepository semesters;
|
||||
private final UserRepository users;
|
||||
|
||||
public DatabaseFixture(RegistrationIdempotencyRepository idempotencies, UserLessonRepository registrations,
|
||||
LessonScheduleRepository schedules, LessonRepository lessons, SubjectRepository subjects,
|
||||
ProfessorRepository professors, SemesterRepository semesters, UserRepository users) {
|
||||
this.idempotencies = idempotencies;
|
||||
this.registrations = registrations;
|
||||
this.schedules = schedules;
|
||||
this.lessons = lessons;
|
||||
this.subjects = subjects;
|
||||
this.professors = professors;
|
||||
this.semesters = semesters;
|
||||
this.users = users;
|
||||
}
|
||||
|
||||
public void reset() {
|
||||
idempotencies.deleteAll();
|
||||
registrations.deleteAll();
|
||||
schedules.deleteAll();
|
||||
lessons.deleteAll();
|
||||
subjects.deleteAll();
|
||||
professors.deleteAll();
|
||||
semesters.deleteAll();
|
||||
users.deleteAll();
|
||||
}
|
||||
|
||||
public RegistrationDataset registrationDataset() {
|
||||
reset();
|
||||
Semester semester = semesters.save(DomainFixtures.openSemester());
|
||||
Professor professor = professors.save(DomainFixtures.professor());
|
||||
Subject subject = subjects.save(DomainFixtures.subject("CS101"));
|
||||
User student = users.save(DomainFixtures.student(2));
|
||||
Lesson lesson = lessons.save(DomainFixtures.lesson(subject, professor, semester));
|
||||
schedules.save(DomainFixtures.schedule(lesson, DayOfWeek.MONDAY, 9, 11));
|
||||
return new RegistrationDataset(semester, professor, subject, student, lesson);
|
||||
}
|
||||
|
||||
public Semester semester(Semester semester) { return semesters.save(semester); }
|
||||
public Professor professor(Professor professor) { return professors.save(professor); }
|
||||
public Subject subject(Subject subject) { return subjects.save(subject); }
|
||||
public User user(User user) { return users.save(user); }
|
||||
public Lesson lesson(Lesson lesson) { return lessons.save(lesson); }
|
||||
public LessonSchedule schedule(LessonSchedule schedule) { return schedules.save(schedule); }
|
||||
public UserLesson registration(UserLesson registration) { return registrations.saveAndFlush(registration); }
|
||||
|
||||
|
||||
public Lesson scheduledLesson(Semester semester, Professor professor, String code, int credit, int capacity,
|
||||
DayOfWeek day, int startHour, int endHour) {
|
||||
Subject subject = subject(DomainFixtures.subject(code, credit));
|
||||
Lesson lesson = lesson(DomainFixtures.lesson(subject, professor, semester, capacity));
|
||||
schedule(DomainFixtures.schedule(lesson, day, startHour, endHour));
|
||||
return lesson;
|
||||
}
|
||||
|
||||
public List<User> students(int count, String prefix) {
|
||||
List<User> result = new ArrayList<>();
|
||||
for (int index = 0; index < count; index++) {
|
||||
result.add(users.save(new User(prefix + index, 2L, UserRole.STUDENT)));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public record RegistrationDataset(
|
||||
Semester semester,
|
||||
Professor professor,
|
||||
Subject subject,
|
||||
User student,
|
||||
Lesson lesson) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
package com.study.course_registration.support.fixture;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
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;
|
||||
|
||||
public final class DomainFixtures {
|
||||
private DomainFixtures() {}
|
||||
|
||||
public static Semester openSemester() {
|
||||
return openSemester(null, "2026-2", 18);
|
||||
}
|
||||
|
||||
public static Semester openSemester(int maxCredits) {
|
||||
return openSemester(null, "semester-" + maxCredits, maxCredits);
|
||||
}
|
||||
|
||||
public static Semester openSemester(String id, String name, int maxCredits) {
|
||||
return new Semester(id, name, TestData.TODAY.minusDays(20), TestData.TODAY.plusDays(100),
|
||||
TestData.NOW.minusSeconds(3600), TestData.NOW.plusSeconds(3600), maxCredits);
|
||||
}
|
||||
|
||||
public static Semester closedSemester() {
|
||||
return closedSemester(null, "closed");
|
||||
}
|
||||
|
||||
public static Semester closedSemester(String id, String name) {
|
||||
return new Semester(id, name, TestData.TODAY.minusDays(100), TestData.TODAY.plusDays(100),
|
||||
TestData.NOW.minusSeconds(7200), TestData.NOW.minusSeconds(3600), 18);
|
||||
}
|
||||
|
||||
public static Semester academicSemester(String name) {
|
||||
return new Semester(name, TestData.TODAY.minusDays(10), TestData.TODAY.plusDays(10),
|
||||
TestData.NOW.minusSeconds(7200), TestData.NOW.minusSeconds(3600), 18);
|
||||
}
|
||||
|
||||
public static Semester futureAcademicSemesterWithOpenRegistration() {
|
||||
return new Semester("future-open", TestData.TODAY.plusDays(30), TestData.TODAY.plusDays(150),
|
||||
TestData.NOW.minusSeconds(3600), TestData.NOW.plusSeconds(3600), 18);
|
||||
}
|
||||
|
||||
public static Semester semester(
|
||||
String id,
|
||||
String name,
|
||||
LocalDate startDate,
|
||||
LocalDate endDate,
|
||||
long registrationStartOffsetSeconds,
|
||||
long registrationEndOffsetSeconds,
|
||||
int maxCredits) {
|
||||
return new Semester(id, name, startDate, endDate,
|
||||
TestData.NOW.plusSeconds(registrationStartOffsetSeconds),
|
||||
TestData.NOW.plusSeconds(registrationEndOffsetSeconds),
|
||||
maxCredits);
|
||||
}
|
||||
|
||||
public static Professor professor() {
|
||||
return new Professor("교수");
|
||||
}
|
||||
|
||||
public static Professor professor(String id) {
|
||||
return new Professor(id, "교수-" + id);
|
||||
}
|
||||
|
||||
public static Subject subject(String code) {
|
||||
return subject(code, 3);
|
||||
}
|
||||
|
||||
public static Subject subject(String code, int credit) {
|
||||
return new Subject(code, code, code + " 설명", credit);
|
||||
}
|
||||
|
||||
public static Subject subject(String id, String code, int credit) {
|
||||
return new Subject(id, code, code, code + " 설명", credit);
|
||||
}
|
||||
|
||||
public static User student(long grade) {
|
||||
return new User("학생-" + grade, grade, UserRole.STUDENT);
|
||||
}
|
||||
|
||||
public static User student(String id, long grade) {
|
||||
return new User(id, "학생-" + id, grade, UserRole.STUDENT);
|
||||
}
|
||||
|
||||
public static User studentNamed(String name, long grade) {
|
||||
return new User(name, grade, UserRole.STUDENT);
|
||||
}
|
||||
|
||||
public static User postgraduate() {
|
||||
return new User("대학원생", 3L, UserRole.POSTGRADUATE);
|
||||
}
|
||||
|
||||
public static Lesson lesson(Subject subject, Professor professor, Semester semester) {
|
||||
return lesson(null, subject.getCode() + " 강의", subject, professor, semester, 30, null, null);
|
||||
}
|
||||
|
||||
public static Lesson lesson(Subject subject, Professor professor, Semester semester, int capacity) {
|
||||
return lesson(null, subject.getCode() + " 강의", subject, professor, semester, capacity, null, null);
|
||||
}
|
||||
|
||||
public static Lesson lesson(
|
||||
String id,
|
||||
String name,
|
||||
Subject subject,
|
||||
Professor professor,
|
||||
Semester semester,
|
||||
int capacity,
|
||||
Long minGrade,
|
||||
UserRole allowedRole) {
|
||||
return new Lesson(id, name, subject, professor, semester, capacity, minGrade, allowedRole);
|
||||
}
|
||||
|
||||
public static LessonSchedule schedule(Lesson lesson, DayOfWeek day, int startHour, int endHour) {
|
||||
return new LessonSchedule(lesson, day, LocalTime.of(startHour, 0), LocalTime.of(endHour, 0));
|
||||
}
|
||||
|
||||
public 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));
|
||||
}
|
||||
|
||||
public static LessonSchedule schedule(DayOfWeek day, int startHour, int endHour) {
|
||||
Semester semester = openSemester("fixture-semester-" + day + startHour, "fixture-" + day + startHour, 18);
|
||||
Subject subject = subject("fixture-subject-" + day + startHour, "FIX" + day.getValue() + startHour, 3);
|
||||
Lesson lesson = lesson(
|
||||
"fixture-lesson-" + day + startHour,
|
||||
"fixture-lesson",
|
||||
subject,
|
||||
professor("fixture-professor-" + day + startHour),
|
||||
semester,
|
||||
30,
|
||||
null,
|
||||
null);
|
||||
return schedule("fixture-schedule-" + day + startHour, lesson, day, startHour, endHour);
|
||||
}
|
||||
|
||||
public static UserLesson registration(User user, Lesson lesson) {
|
||||
return new UserLesson(user, lesson);
|
||||
}
|
||||
|
||||
public static UserLesson registration(String id, User user, Lesson lesson) {
|
||||
return new UserLesson(id, user, lesson);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.study.course_registration.support.fixture;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
|
||||
public final class TestData {
|
||||
public static final Instant NOW = Instant.parse("2026-09-21T03:00:00Z");
|
||||
public static final LocalDate TODAY = LocalDate.of(2026, 9, 21);
|
||||
|
||||
private TestData() {}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.study.course_registration.support.fixture;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.ZoneOffset;
|
||||
|
||||
import org.springframework.boot.test.context.TestConfiguration;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
|
||||
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.RegistrationIdempotencyRepository;
|
||||
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;
|
||||
|
||||
@TestConfiguration(proxyBeanMethods = false)
|
||||
public class TestFixtureConfig {
|
||||
@Bean
|
||||
@Primary
|
||||
Clock testClock() {
|
||||
return Clock.fixed(TestData.NOW, ZoneOffset.UTC);
|
||||
}
|
||||
|
||||
@Bean
|
||||
DatabaseFixture databaseFixture(RegistrationIdempotencyRepository idempotencies,
|
||||
UserLessonRepository registrations, LessonScheduleRepository schedules,
|
||||
LessonRepository lessons, SubjectRepository subjects, ProfessorRepository professors,
|
||||
SemesterRepository semesters, UserRepository users) {
|
||||
return new DatabaseFixture(idempotencies, registrations, schedules, lessons, subjects, professors, semesters, users);
|
||||
}
|
||||
}
|
||||
@@ -1,39 +1,29 @@
|
||||
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 계층에서만
|
||||
* 볼 수 있는 값이 그것이기 때문이다.
|
||||
*/
|
||||
import java.util.Set;
|
||||
|
||||
import com.jayway.jsonpath.JsonPath;
|
||||
|
||||
public final class ApiError extends RuntimeException {
|
||||
private final int status;
|
||||
private final String code;
|
||||
private final String detail;
|
||||
private final String raw;
|
||||
|
||||
ApiError(int status, String code, String detail) {
|
||||
ApiError(int status, String code, String detail, String raw) {
|
||||
super("HTTP " + status + " " + code + " — " + detail);
|
||||
this.status = status;
|
||||
this.code = code;
|
||||
this.detail = detail;
|
||||
this.raw = raw;
|
||||
}
|
||||
|
||||
/** 실제로 내려온 HTTP 상태코드 */
|
||||
public int status() {
|
||||
return status;
|
||||
}
|
||||
public int status() { return status; }
|
||||
public String code() { return code; }
|
||||
public String detail() { return detail; }
|
||||
public String raw() { return raw; }
|
||||
|
||||
/** 응답 바디의 code 필드 (문자열 그대로. enum 변환은 도메인 쪽이 한다) */
|
||||
public String code() {
|
||||
return code;
|
||||
}
|
||||
|
||||
/** 응답 바디의 message 필드 */
|
||||
public String detail() {
|
||||
return detail;
|
||||
public Set<String> fieldNames() {
|
||||
return JsonPath.<Set<String>>read(raw, "$.keys()");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,14 +10,6 @@ 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;
|
||||
|
||||
@@ -26,7 +18,12 @@ public final class JsonApi {
|
||||
}
|
||||
|
||||
public JsonBody post(String path, String jsonBody) {
|
||||
return exchange(MockMvcRequestBuilders.post(path).contentType(MediaType.APPLICATION_JSON).content(jsonBody));
|
||||
}
|
||||
|
||||
public JsonBody post(String path, String jsonBody, String idempotencyKey) {
|
||||
return exchange(MockMvcRequestBuilders.post(path)
|
||||
.header("Idempotency-Key", idempotencyKey)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(jsonBody));
|
||||
}
|
||||
@@ -43,13 +40,13 @@ public final class JsonApi {
|
||||
MockHttpServletResponse response;
|
||||
try {
|
||||
response = mockMvc.perform(request).andReturn().getResponse();
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("요청을 보내지 못했다: " + request, e);
|
||||
} catch (Exception exception) {
|
||||
throw new IllegalStateException("요청을 보내지 못했습니다.", exception);
|
||||
}
|
||||
|
||||
String body = readBody(response);
|
||||
if (response.getStatus() >= 400) {
|
||||
throw new ApiError(response.getStatus(), readField(body, "$.code"), readField(body, "$.message"));
|
||||
throw new ApiError(response.getStatus(), readField(body, "$.code"), readField(body, "$.message"), body);
|
||||
}
|
||||
return new JsonBody(response.getStatus(), body);
|
||||
}
|
||||
@@ -58,19 +55,17 @@ public final class JsonApi {
|
||||
try {
|
||||
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
|
||||
return response.getContentAsString(StandardCharsets.UTF_8);
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("응답 본문을 읽지 못했다", e);
|
||||
} catch (Exception exception) {
|
||||
throw new IllegalStateException("응답 본문을 읽지 못했습니다.", exception);
|
||||
}
|
||||
}
|
||||
|
||||
private static String readField(String body, String path) {
|
||||
if (body == null || body.isBlank()) {
|
||||
return "(빈 응답 본문)";
|
||||
}
|
||||
if (body == null || body.isBlank()) return "(빈 응답 본문)";
|
||||
try {
|
||||
return String.valueOf(JsonPath.<Object>read(body, path));
|
||||
} catch (RuntimeException e) {
|
||||
return "(" + path + " 없음: " + body + ")";
|
||||
} catch (RuntimeException exception) {
|
||||
return "(" + path + " 없음)";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,16 +2,8 @@ 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;
|
||||
@@ -21,28 +13,8 @@ public final class JsonBody {
|
||||
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;
|
||||
}
|
||||
public int status() { return status; }
|
||||
public <T> T at(String jsonPath) { return JsonPath.read(raw, jsonPath); }
|
||||
public Set<String> fieldNames() { return JsonPath.read(raw, "$.keys()"); }
|
||||
public String raw() { return raw; }
|
||||
}
|
||||
|
||||
@@ -1,19 +1,25 @@
|
||||
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:
|
||||
flyway:
|
||||
locations: classpath:db/migration/h2
|
||||
jpa:
|
||||
hibernate:
|
||||
ddl-auto: create-drop
|
||||
open-in-view: false
|
||||
hibernate:
|
||||
ddl-auto: validate
|
||||
properties:
|
||||
hibernate:
|
||||
generate_statistics: true
|
||||
h2:
|
||||
console:
|
||||
enabled: false
|
||||
|
||||
app:
|
||||
seed:
|
||||
enabled: false
|
||||
|
||||
springdoc:
|
||||
api-docs:
|
||||
enabled: false
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
a b
|
||||
1
|
||||
|
@@ -0,0 +1,2 @@
|
||||
name optional number
|
||||
alpha 3
|
||||
|
Reference in New Issue
Block a user