CH 03. 인텔리제이 실습 - To do List 구현하기
07. 테스트 코드 작성
package org.example.service;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.when;
import java.util.Optional;
import org.example.model.TodoEntity;
import org.example.model.TodoRequest;
import org.example.repository.TodoRepository;
import org.junit.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.AdditionalAnswers;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.web.server.ResponseStatusException;
@ExtendWith(MockitoExtension.class)
public class TodoServiceTest {
@InjectMocks
private TodoService todoService;
@Mock
private TodoRepository todoRepository;
@Test
public void add() {
when(this.todoRepository.save(any(TodoEntity.class)))
.then(AdditionalAnswers.returnsFirstArg());
TodoRequest request = new TodoRequest();
request.setTitle("test title");
TodoEntity actual = this.todoService.add(request);
assertEquals(1L, actual.getId());
assertEquals("test title", actual.getTitle());
}
@Test
public void searchById() {
TodoEntity todo = new TodoEntity();
todo.setTitle("test");
todo.setId(123L);
todo.setOrder(0L);
todo.setCompleted(false);
Optional<TodoEntity> expected = Optional.of(todo);
given(this.todoRepository.findById(anyLong()))
.willReturn(expected);
TodoEntity actual = this.todoService.searchById(123L);
assertEquals(actual.getId(), 123L);
assertEquals(actual.getOrder(), 0L);
assertFalse(actual.getCompleted());
assertEquals(actual.getTitle(), "test");
}
@Test
public void searchByIdFailed() {
given(this.todoRepository.findById(anyLong())).willReturn(Optional.empty());
assertThrows(ResponseStatusException.class, () -> {
this.todoService.searchById(123L);
});
}
}
<TodoServiceTest.java>
package org.example.controller;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.example.controller.TodoController;
import org.example.model.TodoEntity;
import org.example.model.TodoRequest;
import org.example.service.TodoService;
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.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.server.ResponseStatusException;
@WebMvcTest(TodoController.class)
public class TodoControllerTest {
@Autowired
MockMvc mvc;
@MockBean
private TodoService todoService;
private TodoEntity expected;
@BeforeEach
void setup() {
this.expected = new TodoEntity();
this.expected.setId(123L);
this.expected.setTitle("test");
this.expected.setOrder(0L);
this.expected.setCompleted(false);
}
@Test
void create() throws Exception {
when(this.todoService.add(any(TodoRequest.class)))
.then((i) -> {
TodoRequest request = i.getArgument(0, TodoRequest.class);
return new TodoEntity(this.expected.getId(), request.getTitle(), request.getOrder(), request.getCompleted());
});
TodoRequest request = new TodoRequest();
request.setTitle(this.expected.getTitle());
ObjectMapper mapper = new ObjectMapper();
String content = mapper.writeValueAsString(request);
mvc.perform(post("/")
.contentType(MediaType.APPLICATION_JSON)
.content(content))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value(expected.getId()))
.andExpect(jsonPath("$.title").value(expected.getTitle()))
.andExpect(jsonPath("$.order").value(expected.getOrder()))
.andExpect(jsonPath("$.completed").value(expected.getCompleted()));
}
@Test
void readOne() throws Exception {
given(todoService.searchById(123L)).willReturn(expected);
mvc.perform(get("/123"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.id").value(expected.getId()))
.andExpect(jsonPath("$.title").value(expected.getTitle()))
.andExpect(jsonPath("$.order").value(expected.getOrder()))
.andExpect(jsonPath("$.completed").value(expected.getCompleted()));
}
@Test
void readOneException() throws Exception {
given(todoService.searchById(123L)).willThrow(new ResponseStatusException(HttpStatus.NOT_FOUND));
mvc.perform(get("/123"))
.andExpect(status().isNotFound());
}
@Test
void readAll() throws Exception {
List<TodoEntity> mockList = new ArrayList<>();
int expectedLength = 10;
for (int i = 0; i < expectedLength; i++) {
mockList.add(mock(TodoEntity.class));
}
given(todoService.searchAll()).willReturn(mockList);
mvc.perform(get("/"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.length()").value(expectedLength));
}
@Test
void deleteAll() throws Exception {
mvc.perform(delete("/"))
.andExpect(status().isOk());
}
}
<TodoControllerTest>
* 처음 프로젝트 동작 시 org.mockito.······에서 mockito패키지가 없는 문제가 발생했다.
구글링과 교육 자료를 통해
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
implementation 'junit:junit:4.13.1'
spring boot package의 spring-boot-starter-test항목(정확한 명칭을 모르겠다...)에 포함되어 있음을 알 수 있었다.
* 테스트가 제대로 진행되지 않아서 천천히 다시 들으면서 해봐야할 것 같다...
----------------------------------------------------------------------------------------------------------------------------------
https:/bit.ly/37BpXic
'[패스트캠퍼스] Spring' 카테고리의 다른 글
패스트캠퍼스 챌린지 6일차 (0) | 2022.01.29 |
---|---|
패스트캠퍼스 챌린지 5일차 (0) | 2022.01.28 |
패스트캠퍼스 챌린지 3일차 (0) | 2022.01.26 |
패스트캠퍼스 챌린지 2일차 (0) | 2022.01.25 |
패스트캠퍼스 챌린지 1일차 - Intellij 가이드 (0) | 2022.01.24 |
댓글