Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,11 @@ dependencies {

// Test
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation "org.junit.jupiter:junit-jupiter:5.8.1"
testImplementation "org.testcontainers:testcontainers:2.0.1"
testImplementation "org.testcontainers:testcontainers-junit-jupiter:2.0.1"
testImplementation "org.testcontainers:testcontainers-mysql:2.0.1"
testImplementation 'org.springframework.boot:spring-boot-testcontainers'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'

// Swagger
Expand Down
19 changes: 19 additions & 0 deletions src/test/java/leets/weeth/config/TestContainersConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package leets.weeth.config;

import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.testcontainers.service.connection.ServiceConnection;
import org.springframework.context.annotation.Bean;
import org.testcontainers.mysql.MySQLContainer;
import org.testcontainers.utility.DockerImageName;

@TestConfiguration
public class TestContainersConfig {
private static final String MYSQL_IMAGE = "mysql:8.0.41";

@Bean
@ServiceConnection
public MySQLContainer mysqlContainer() {
return new MySQLContainer(DockerImageName.parse(MYSQL_IMAGE))
.withReuse(true);
}
}
25 changes: 25 additions & 0 deletions src/test/java/leets/weeth/config/TestContainersTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package leets.weeth.config;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.context.annotation.Import;
import org.testcontainers.mysql.MySQLContainer;

import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;

@DataJpaTest
@Import(TestContainersConfig.class)
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
class TestContainersTest {
@Autowired
private MySQLContainer mysqlContainer;

@Test
void 설정파일로_주입된_컨테이너_정상_동작_테스트() {
assertThat(mysqlContainer).isNotNull();
assertThat(mysqlContainer.isRunning()).isTrue();
System.out.println("Container JDBC URL: " + mysqlContainer.getJdbcUrl());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
package leets.weeth.domain.schedule.domain.repository;

import leets.weeth.config.TestContainersConfig;
import leets.weeth.domain.schedule.domain.entity.Event;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.context.annotation.Import;

import java.time.LocalDateTime;
import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;

@DataJpaTest
@Import(TestContainersConfig.class)
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
class EventRepositoryTest {

@Autowired
private EventRepository eventRepository;

@BeforeEach
void setUp() {
LocalDateTime now = LocalDateTime.now();
Event event1 = Event.builder()
.title("Event 1")
.start(now.plusDays(1))
.end(now.plusDays(2))
.cardinal(1)
.build();

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

setUp 내부 객체 생성 로직도 , Fixture로 처리할 수 있지 않을까요!? 😲❔

Event event2 = Event.builder()
.title("Event 2")
.start(now.plusDays(3))
.end(now.plusDays(4))
.cardinal(1)
.build();

Event event3 = Event.builder()
.title("Event 3")
.start(now.plusDays(5))
.end(now.plusDays(6))
.cardinal(2)
.build();

eventRepository.saveAll(List.of(event1, event2, event3));
}
Comment on lines +25 to +50
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

테스트 데이터 생성 방식을 개선하세요.

LocalDateTime.now()setUp과 테스트 메서드에서 각각 호출하면 시간 차이로 인해 테스트가 불안정해질 수 있습니다. 또한 PR 설명에서 "공통 테스트 데이터는 fixture로 정의하여 중복을 방지한다"고 명시했지만, 이 테스트는 ScheduleTestFixture를 사용하지 않고 있습니다.

다음과 같이 개선하는 것을 권장합니다:

 @BeforeEach
 void setUp() {
-    LocalDateTime now = LocalDateTime.now();
+    LocalDateTime now = LocalDateTime.of(2024, 1, 1, 0, 0);
     Event event1 = Event.builder()
             .title("Event 1")
             .start(now.plusDays(1))
             .end(now.plusDays(2))
             .cardinal(1)
             .build();

     Event event2 = Event.builder()
             .title("Event 2")
             .start(now.plusDays(3))
             .end(now.plusDays(4))
             .cardinal(1)
             .build();

     Event event3 = Event.builder()
             .title("Event 3")
             .start(now.plusDays(5))
             .end(now.plusDays(6))
             .cardinal(2)
             .build();

     eventRepository.saveAll(List.of(event1, event2, event3));
 }

또한 ScheduleTestFixture를 활용하여 코드 중복을 줄이는 것도 고려해보세요.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
@BeforeEach
void setUp() {
LocalDateTime now = LocalDateTime.now();
Event event1 = Event.builder()
.title("Event 1")
.start(now.plusDays(1))
.end(now.plusDays(2))
.cardinal(1)
.build();
Event event2 = Event.builder()
.title("Event 2")
.start(now.plusDays(3))
.end(now.plusDays(4))
.cardinal(1)
.build();
Event event3 = Event.builder()
.title("Event 3")
.start(now.plusDays(5))
.end(now.plusDays(6))
.cardinal(2)
.build();
eventRepository.saveAll(List.of(event1, event2, event3));
}
@BeforeEach
void setUp() {
LocalDateTime now = LocalDateTime.of(2024, 1, 1, 0, 0);
Event event1 = Event.builder()
.title("Event 1")
.start(now.plusDays(1))
.end(now.plusDays(2))
.cardinal(1)
.build();
Event event2 = Event.builder()
.title("Event 2")
.start(now.plusDays(3))
.end(now.plusDays(4))
.cardinal(1)
.build();
Event event3 = Event.builder()
.title("Event 3")
.start(now.plusDays(5))
.end(now.plusDays(6))
.cardinal(2)
.build();
eventRepository.saveAll(List.of(event1, event2, event3));
}
🤖 Prompt for AI Agents
In
src/test/java/leets/weeth/domain/schedule/domain/repository/EventRepositoryTest.java
around lines 25-50, the setup uses LocalDateTime.now() directly which can
produce flaky tests and duplicates fixture logic; replace dynamic now() calls by
obtaining a single fixed reference time (e.g., a constant or from
ScheduleTestFixture) at the start of setUp and use that same reference in all
event creations, and refactor to use ScheduleTestFixture methods to create the
three events (or a single helper that returns prebuilt Event instances) then
saveAll those fixtures so tests share common, deterministic test data and avoid
duplicated construction logic.


@Test
void testFindByStartLessThanEqualAndEndGreaterThanEqualOrderByStartAsc() {
// given
LocalDateTime start = LocalDateTime.now().plusDays(2);
LocalDateTime end = LocalDateTime.now().plusDays(7);

// when
List<Event> events = eventRepository.findByStartLessThanEqualAndEndGreaterThanEqualOrderByStartAsc(end, start);

// then
assertThat(events)
.hasSize(2)
.extracting(Event::getTitle)
.containsExactly("Event 2", "Event 3"); // 순서와 구성이 모두 일치하는지
}
Comment on lines +52 to +66
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

쿼리 메서드 호출의 파라미터 순서와 테스트 로직을 검증하세요.

메서드 호출 시 (end, start) 순서로 파라미터를 전달하는 것이 직관적이지 않으며, 테스트 예상 결과에 문제가 있을 수 있습니다.

다음 사항들을 확인해주세요:

  1. 파라미터 순서: 메서드명에 StartLessThanEqual이 먼저 나오는데 (end, start) 순서로 전달하는 것은 혼란을 야기합니다. 메서드 시그니처를 확인하여 의도된 순서인지 검증이 필요합니다.

  2. 테스트 로직 오류:

    • Event 1: end=now+2 (정확히 범위의 시작점)
    • 쿼리 범위: [now+2, now+7]
    • end >= start 조건에 따라 Event 1도 포함되어야 하는데, 예상 결과에서 제외되어 있습니다.
  3. LocalDateTime.now() 재사용: setUp에서 사용한 now와 테스트 메서드에서 새로 호출한 LocalDateTime.now()가 달라서 Event 1이 범위에서 벗어날 수도 있습니다. 이는 테스트를 불안정하게 만듭니다.

setUp에서 정의한 고정된 LocalDateTime을 클래스 필드로 저장하여 테스트 메서드에서도 재사용하는 것을 권장합니다.



---

🏁 Script executed:

```shell
#!/bin/bash
# Find EventRepository to check method signature
find . -type f -name "*EventRepository*" | head -20

Length of output: 169


🏁 Script executed:

#!/bin/bash
# Find and display the EventRepositoryTest class, particularly setUp and the test method
rg -n "class EventRepositoryTest" -A 100 src/test/java/leets/weeth/domain/schedule/domain/repository/ | head -150

Length of output: 7338


🏁 Script executed:

#!/bin/bash
# Search for the method definition in repository
rg -n "findByStartLessThanEqualAndEndGreaterThanEqualOrderByStartAsc" . -A 2

Length of output: 3076


메서드 파라미터 순서 불일치와 테스트 로직 오류를 수정하세요.

EventRepository와 MeetingRepository의 메서드 파라미터 순서가 서로 다릅니다:

  • EventRepository: (LocalDateTime end, LocalDateTime start)
  • MeetingRepository: (LocalDateTime start, LocalDateTime end)

그런데 두 서비스 모두 (end, start) 순서로 호출하므로 MeetingGetService에서 잘못된 파라미터가 전달됩니다.

또한 테스트 예상 결과가 잘못되었습니다:

setUp의 Event 1 (start=now+1, end=now+2)은 쿼리 조건 start <= now+7 AND end >= now+2를 만족하므로 결과에 포함되어야 합니다. 현재 예상 결과에서 Event 1을 제외하는 것은 오류입니다.

권장 사항:

  1. 파라미터 순서를 통일하세요. 메서드명의 의미(StartLessThanEqual, EndGreaterThanEqual)에 맞춰 (LocalDateTime start, LocalDateTime end) 순서로 정렬하는 것을 권장합니다.
  2. 테스트 예상 결과를 3개 이벤트 모두 포함하도록 수정하세요: .hasSize(3).containsExactly("Event 1", "Event 2", "Event 3")
  3. LocalDateTime.now()를 setUp에서 클래스 필드로 저장하여 재사용하세요.
🤖 Prompt for AI Agents
In
src/test/java/leets/weeth/domain/schedule/domain/repository/EventRepositoryTest.java
around lines 52-66: the test calls the repository with reversed parameter order
and asserts the wrong expected results; unify repository method signatures to
(LocalDateTime start, LocalDateTime end) for both EventRepository and
MeetingRepository (rename params if necessary), update all call sites (e.g.,
MeetingGetService and the test) to pass (start, end) in that order, modify the
test to use a single LocalDateTime "now" captured in setUp and reuse it (avoid
multiple LocalDateTime.now() calls), and change the assertions to expect all
three events: .hasSize(3) and .containsExactly("Event 1", "Event 2", "Event 3").


@Test
void testFindAllByCardinal() {
// given
int cardinal = 1;

// when
List<Event> events = eventRepository.findAllByCardinal(cardinal);

// then
assertThat(events)
.hasSize(2)
.extracting(Event::getTitle)
.containsExactly("Event 1", "Event 2");
}
Comment on lines +68 to +81
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

쿼리 결과 순서에 대한 가정을 검증하세요.

findAllByCardinal 메서드는 정렬 순서를 명시하지 않는데, containsExactly를 사용하여 특정 순서를 기대하고 있습니다.

Spring Data JPA는 메서드명에 OrderBy가 없거나 @OrderBy 어노테이션이 없으면 쿼리 결과의 순서를 보장하지 않습니다. 다음 중 하나를 선택하세요:

  1. 순서가 중요하다면: 쿼리 메서드명을 findAllByCardinalOrderByStartAsc 등으로 변경하여 명시적으로 정렬 지정
  2. 순서가 중요하지 않다면: containsExactlyInAnyOrder로 변경하여 순서에 무관하게 검증
 assertThat(events)
         .hasSize(2)
         .extracting(Event::getTitle)
-        .containsExactly("Event 1", "Event 2");
+        .containsExactlyInAnyOrder("Event 1", "Event 2");

쿼리 메서드의 실제 구현을 확인하여 정렬이 보장되는지 검증해주세요.



---

🏁 Script executed:

```shell
#!/bin/bash
# Find EventRepository interface/class definition
fd -e java -e kt | xargs grep -l "findAllByCardinal" | head -20

Length of output: 893


🏁 Script executed:

#!/bin/bash
# Locate the EventRepository file
fd "EventRepository\." -e java -e kt

Length of output: 80


🏁 Script executed:

#!/bin/bash
# Find test setup - look for @BeforeEach or test data initialization in EventRepositoryTest
fd "EventRepositoryTest" -e java

Length of output: 84



---

🏁 Script executed:

```shell
#!/bin/bash
# Get EventRepository method definition
cat src/main/java/leets/weeth/domain/schedule/domain/repository/EventRepository.java

Length of output: 472


🏁 Script executed:

#!/bin/bash
# Get the full test file to see setup and all test methods
cat src/test/java/leets/weeth/domain/schedule/domain/repository/EventRepositoryTest.java

Length of output: 2544



---

🏁 Script executed:

```shell
#!/bin/bash
# Check Event entity for @OrderBy or default ordering
fd "Event\.java" -path "*/schedule/domain/entity/*" -e java

Length of output: 168


🏁 Script executed:

#!/bin/bash
# Get Event entity definition
cat src/main/java/leets/weeth/domain/schedule/domain/entity/Event.java

Length of output: 555



---

🏁 Script executed:

```shell
#!/bin/bash
# Find Schedule parent class
fd "Schedule\.java" -path "*/schedule/domain/entity/*"

Length of output: 168


🏁 Script executed:

#!/bin/bash
# Get Schedule entity definition
cat src/main/java/leets/weeth/domain/schedule/domain/entity/Schedule.java

Length of output: 1406


쿼리 메서드의 정렬 순서 미지정으로 인한 테스트 불안정성 문제 확인됨

findAllByCardinal 메서드에는 정렬을 명시하는 어떤 장치도 없습니다.

문제점:

  • EventRepositoryfindAllByCardinal(int cardinal) 메서드에 OrderBy 절이나 @OrderBy 어노테이션이 없음
  • Event 엔티티와 Schedule 부모 클래스에도 기본 정렬 지정이 없음
  • Spring Data JPA는 명시적 정렬이 없으면 결과 순서를 보장하지 않음
  • containsExactly는 순서와 내용을 모두 검증하므로, 순서 보장 없이 사용 시 테스트가 불안정할 수 있음

해결 방안 (둘 중 선택):

  1. 순서가 중요하지 않다면: 정렬 순서를 명시하지 않고 검증하도록 변경

    assertThat(events)
            .hasSize(2)
            .extracting(Event::getTitle)
    -        .containsExactly("Event 1", "Event 2");
    +        .containsExactlyInAnyOrder("Event 1", "Event 2");
  2. 순서가 중요하다면: 리포지토리 메서드명을 변경하여 정렬 명시

    • findAllByCardinalOrderByIdAsc 또는 다른 정렬 기준 지정
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
@Test
void testFindAllByCardinal() {
// given
int cardinal = 1;
// when
List<Event> events = eventRepository.findAllByCardinal(cardinal);
// then
assertThat(events)
.hasSize(2)
.extracting(Event::getTitle)
.containsExactly("Event 1", "Event 2");
}
@Test
void testFindAllByCardinal() {
// given
int cardinal = 1;
// when
List<Event> events = eventRepository.findAllByCardinal(cardinal);
// then
assertThat(events)
.hasSize(2)
.extracting(Event::getTitle)
.containsExactlyInAnyOrder("Event 1", "Event 2");
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
package leets.weeth.domain.schedule.domain.repository;

import leets.weeth.config.TestContainersConfig;
import leets.weeth.domain.schedule.domain.entity.Meeting;
import leets.weeth.domain.schedule.domain.entity.enums.MeetingStatus;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.context.annotation.Import;

import java.time.LocalDateTime;
import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;

@DataJpaTest
@Import(TestContainersConfig.class)
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
class MeetingRepositoryTest {
@Autowired
private MeetingRepository meetingRepository;

@BeforeEach
void setUp() {
Meeting meeting1 = Meeting.builder()
.title("Meeting 1")
.start(LocalDateTime.now().plusDays(1))
.end(LocalDateTime.now().plusDays(2))
.code(1111)
.cardinal(1)
.meetingStatus(MeetingStatus.OPEN)
.build();
Comment on lines +27 to +34
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

픽스쳐로 간단하게 할수있을거같아요!


Meeting meeting2 = Meeting.builder()
.title("Meeting 2")
.start(LocalDateTime.now().plusDays(3))
.end(LocalDateTime.now().plusDays(4))
.code(2222)
.cardinal(1)
.meetingStatus(MeetingStatus.OPEN)
.build();

Meeting meeting3 = Meeting.builder()
.title("Meeting 3")
.start(LocalDateTime.now().plusDays(5))
.end(LocalDateTime.now().plusDays(6))
.code(3333)
.cardinal(2)
.meetingStatus(MeetingStatus.CLOSE)
.build();

meetingRepository.saveAll(java.util.List.of(meeting1, meeting2, meeting3));
}


@Test
void findByStartLessThanEqualAndEndGreaterThanEqualOrderByStartAsc() {
// given
LocalDateTime start = LocalDateTime.now().plusDays(1);
LocalDateTime end = LocalDateTime.now().plusDays(4);

// when
List<Meeting> meetings = meetingRepository.findByStartLessThanEqualAndEndGreaterThanEqualOrderByStartAsc(end, start);

// then
assertThat(meetings)
.hasSize(2)
.extracting(Meeting::getTitle)
.containsExactly("Meeting 1", "Meeting 2");
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

의도나 명확성이 잘 보이게끔 설계된 코드로 보입니다!
허나 메서드명이 긴만큼 .. 추가 설명이나 네이밍을 좀 이해하기 쉽게 해주면 좋을 것 같아요 😊


@Test
void findAllByCardinalOrderByStartAsc() {
// given
int cardinal = 1;

// when
List<Meeting> meetings = meetingRepository.findAllByCardinalOrderByStartAsc(cardinal);

// then
assertThat(meetings)
.hasSize(2)
.extracting(Meeting::getTitle)
.containsExactly("Meeting 1", "Meeting 2");
}

@Test
void findAllByCardinalOrderByStartDesc() {
// given
int cardinal = 1;

// when
List<Meeting> meetings = meetingRepository.findAllByCardinalOrderByStartDesc(cardinal);

// then
assertThat(meetings)
.hasSize(2)
.extracting(Meeting::getTitle)
.containsExactly("Meeting 2", "Meeting 1");
}

@Test
void findAllByCardinal() {
// given
int cardinal = 1;

// when
List<Meeting> meetings = meetingRepository.findAllByCardinal(cardinal);

// then
assertThat(meetings)
.hasSize(2)
.extracting(Meeting::getTitle)
.containsExactlyInAnyOrder("Meeting 1", "Meeting 2");
}

@Test
void findAllByMeetingStatusAndEndBeforeOrderByEndAsc() {
// given
MeetingStatus status = MeetingStatus.OPEN;

// when
List<Meeting> meetings = meetingRepository.findAllByMeetingStatusAndEndBeforeOrderByEndAsc(status, LocalDateTime.now().plusDays(5));

// then
assertThat(meetings)
.hasSize(2)
.extracting(Meeting::getTitle)
.containsExactly("Meeting 1", "Meeting 2");

assertThat(meetings)
.extracting(Meeting::getMeetingStatus)
.containsOnly(MeetingStatus.OPEN)
.doesNotContain(MeetingStatus.CLOSE);
}

@Test
void findAllByOrderByStartDesc() {
// when
List<Meeting> meetings = meetingRepository.findAllByOrderByStartDesc();

// then
assertThat(meetings)
.hasSize(3)
.extracting(Meeting::getTitle)
.containsExactly("Meeting 3", "Meeting 2", "Meeting 1");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package leets.weeth.domain.schedule.domain.service;

import leets.weeth.domain.schedule.application.exception.EventNotFoundException;
import leets.weeth.domain.schedule.application.mapper.ScheduleMapper;
import leets.weeth.domain.schedule.domain.entity.Event;
import leets.weeth.domain.schedule.domain.repository.EventRepository;
import leets.weeth.domain.schedule.test.fixture.ScheduleTestFixture;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import java.util.Optional;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@ExtendWith(MockitoExtension.class)
class EventGetServiceTest {

@Mock
private EventRepository eventRepository;

@Mock
private ScheduleMapper scheduleMapper;

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ScheduleMapper 이녀석은 위 파일에서 사용하지 않는 것 같은데 ... 작성하신 이유가 있을까요!?
필요없다면 제거하는게 좋아보입니다 !😄

@InjectMocks
private EventGetService eventGetService;

private Event testEvent;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

요 친구만 Mock이 아닌 일반 객체로 만든 이유가 있을까요!? 궁금합니다.
아래의 코드들로 짐작해보아 .. 단순 반환용이므로 의도하신걸까요!?


@BeforeEach
void setUp() {
testEvent = ScheduleTestFixture.createEvent();
}

@Test
void testFind() {
// given
when(eventRepository.findById(1L))
.thenReturn(Optional.of(testEvent));

// when
Event event = eventGetService.find(1L);

// then
assertThat(event).isEqualTo(testEvent);
verify(eventRepository).findById(1L);
}

@Test
void testFindNotFound() {
// given
Long id = 999L;
when(eventRepository.findById(id)).thenReturn(Optional.empty());

// when & then
// 이벤트가 존재하지 않을 때 예외가 발생하는지 확인
assertThatThrownBy(() -> eventGetService.find(id))
.isInstanceOf(EventNotFoundException.class);
verify(eventRepository).findById(id);
}
}
Loading