Skip to content
Open
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
133 changes: 133 additions & 0 deletions hiking-api/src/test/java/com/dseoki/api/hiking/HikingServiceTest.java
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 {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Mock repository에서 예외를 발생시키는 테스트를 추가하시면 좋습니다.


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));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The 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("예외가 발생하지 않으면 출력됨!! 예외 이후에 발생되는 부분 작성 해야 함");
}

}