-
Notifications
You must be signed in to change notification settings - Fork 1
tdd mock test #13
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
dseoki
wants to merge
2
commits into
main
Choose a base branch
from
feature/tdd-first
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
tdd mock test #13
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
133 changes: 133 additions & 0 deletions
133
hiking-api/src/test/java/com/dseoki/api/hiking/HikingServiceTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,133 @@ | ||
| package com.dseoki.api.hiking; | ||
|
|
||
| import com.dseoki.api.entity.Hiking; | ||
| import com.dseoki.api.hiking.domain.HikingDto; | ||
| import com.dseoki.api.hiking.domain.HikingResponse; | ||
| import org.junit.jupiter.api.Test; | ||
| import org.springframework.beans.factory.annotation.Autowired; | ||
| import org.springframework.boot.test.context.SpringBootTest; | ||
| import org.springframework.boot.test.mock.mockito.MockBean; | ||
| import org.springframework.core.io.ResourceLoader; | ||
|
|
||
| import java.time.LocalDateTime; | ||
| import java.util.Arrays; | ||
| import java.util.List; | ||
|
|
||
| import static org.assertj.core.api.Assertions.assertThat; | ||
| import static org.assertj.core.api.Assertions.assertThatThrownBy; | ||
| import static org.mockito.Mockito.*; | ||
|
|
||
| @SpringBootTest | ||
| public class HikingServiceTest { | ||
|
|
||
| private final ResourceLoader resourceLoader; | ||
|
|
||
| // SpringBootTest는 전체 컨텍스트를 로드하고 빈을 주입한다. 또한 모든 인스턴스를 Mocking 한다. @MockBean 어노테이션을 생략할 수 있다. | ||
| private final HikingService hikingService; | ||
|
|
||
| @MockBean | ||
| HikingRepository hikingRepository; | ||
|
|
||
| @Autowired | ||
| public HikingServiceTest(ResourceLoader resourceLoader, HikingService hikingService) { | ||
| this.resourceLoader = resourceLoader; | ||
| this.hikingService = hikingService; | ||
| } | ||
|
|
||
| @Test | ||
| public void searchHikingExceptionTest() { | ||
| when(hikingRepository.findAll()) | ||
| .thenThrow(new RuntimeException("Database connection error")); | ||
|
|
||
| assertThatThrownBy(() -> { | ||
| hikingService.searchHiking(); | ||
| }) | ||
| .isInstanceOf(RuntimeException.class) | ||
| .hasMessage("Database connection error"); | ||
| } | ||
|
|
||
| @Test | ||
| public void searchHikingTest() { | ||
| Hiking hiking1 = new Hiking(); | ||
| hiking1.setId(1333L); | ||
| hiking1.setHikeStartDate(LocalDateTime.of(2024, 2, 15, 9, 00)); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 반복되어 사용되는 LocalDateTime.of(2024, 2, 15, 9, 00)와 같은 값은 상수로 처리하시면 좋을 것 같습니다. |
||
| hiking1.setHikeEndDate(LocalDateTime.of(2024, 2, 15, 9, 30)); | ||
|
|
||
| Hiking hiking2 = new Hiking(); | ||
| hiking2.setId(2L); | ||
| hiking2.setHikeStartDate(LocalDateTime.of(2024, 5, 15, 9, 00)); | ||
| hiking2.setHikeEndDate(LocalDateTime.of(2024, 5, 15, 9, 30)); | ||
|
|
||
| when(hikingRepository.findAll()) | ||
| .thenReturn(Arrays.asList(hiking1, hiking2)) | ||
| .thenThrow(new RuntimeException("Database connection error")); | ||
|
|
||
| List<HikingResponse> result = hikingService.searchHiking(); | ||
|
|
||
| // assertj 사용 권장: 가독성이 좋음 | ||
| assertThat(result.size()).isEqualTo(2); | ||
| assertThat(result.get(0).getId()).isEqualTo(1333L); | ||
| } | ||
|
|
||
| @Test | ||
| public void insertHikingExceptionTest() { | ||
| HikingDto hikingDto = new HikingDto(); | ||
|
|
||
| doThrow(new IllegalArgumentException("Failed to save hiking data")).when(hikingRepository).save(any(Hiking.class)); | ||
|
|
||
| assertThatThrownBy(() -> { | ||
| hikingService.insertHiking(hikingDto); | ||
| }) | ||
| .isInstanceOf(IllegalArgumentException.class) | ||
| .hasMessage("Failed to save hiking data"); | ||
| } | ||
|
|
||
| @Test | ||
| public void insertHikingTest() { | ||
| HikingDto hikingDto = new HikingDto(); | ||
| hikingDto.setTitle("Hiking test"); | ||
| hikingDto.setHikeStartDate("2021-02-13 09:00"); | ||
| hikingDto.setHikeEndDate("2021-02-13 18:00"); | ||
| hikingDto.setDistance(10); | ||
| hikingDto.setElevation(10); | ||
| hikingDto.setEstimatedDuration(10); | ||
| hikingDto.setDescription("mock tdd test description..."); | ||
|
|
||
| // 테스트 실행 | ||
| hikingService.insertHiking(hikingDto); | ||
|
|
||
| // Mock 리포지토리의 save 메서드가 호출되었는지 확인 | ||
| verify(hikingRepository, times(1)).save(any(Hiking.class)); | ||
| } | ||
|
|
||
| @Test | ||
| public void 예외테스트1() { | ||
| /** | ||
| * isInstanceOf()은 발생한 예외가 해당 인스턴스인지 확인한다. | ||
| * hasMessageContaining()는 예외 메시지가 특정 문자열을 포함하는지 확인힌다. | ||
| */ | ||
| assertThatThrownBy(() -> { throw new Exception("error 발생한 곳!!"); }) | ||
| .isInstanceOf(Exception.class) | ||
| .hasMessageContaining("error 발생한 곳!!"); | ||
| } | ||
| @Test | ||
| public void 예외테스트2() { | ||
| // assertj 권장 방식 | ||
| assertThatThrownBy(() -> { | ||
| String[] str = {"one", "two", "three"}; | ||
| System.out.println(str[4]); | ||
| }) | ||
| .isInstanceOf(ArrayIndexOutOfBoundsException.class); | ||
|
|
||
| /** junit5 방식 | ||
| assertThrows(ArrayIndexOutOfBoundsException.class, () -> { | ||
| String[] str = {"one", "two", "three"}; | ||
| System.out.println(str[4]); | ||
| }, | ||
| "ArrayIndexOutOfBoundsException이 아님!!"); | ||
| */ | ||
|
|
||
| System.out.println("예외가 발생하지 않으면 출력됨!! 예외 이후에 발생되는 부분 작성 해야 함"); | ||
| } | ||
|
|
||
| } | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Mock repository에서 예외를 발생시키는 테스트를 추가하시면 좋습니다.