Skip to content
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

[#9] Task CRUD API 스펙 정의 및 생성 #10

Merged
merged 22 commits into from
Sep 2, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
2365d68
refactor: HealthController 파일 이동
olivejua Aug 16, 2024
e4ebac4
docs: README.md git flow 내용 추가
olivejua Aug 17, 2024
52e6b7a
chore: lombok 플러그인 추가
olivejua Aug 17, 2024
43aaeb8
feat: ApiResponse 클래스 생성
olivejua Aug 17, 2024
84843ea
refactor: ErrorDetail 클래스명 변경
olivejua Aug 17, 2024
d57bbc5
chore: restDocs 설정 추가
olivejua Aug 18, 2024
6f626ab
feat: Task 단건조회 API 생성
olivejua Aug 18, 2024
6942547
feat: Task 생성 API 생성
olivejua Aug 19, 2024
55639b5
feat: Task 삭제 API 생성
olivejua Aug 19, 2024
7c1a8a2
feat: ApiControllerAdvice 생성 및 실패테스트케이스 추가
olivejua Aug 19, 2024
00871e2
docs: index.adoc 작성
olivejua Aug 19, 2024
dfe4b06
style: todo 주석 제거
olivejua Aug 19, 2024
369e578
refactor: NoData 클래스 제거
olivejua Aug 19, 2024
e05ff3a
chore: bootJar태스크의 dependson 추가
olivejua Aug 19, 2024
fcaedc8
refactor: Custom Exception 제거 및 Error Code 통일
olivejua Aug 20, 2024
e50bd14
refactor: TaskControllerTest 클래스명 변경
olivejua Aug 20, 2024
39a0a26
refactor: TAskCreateRequest 의 파라미터 유효성 검증 및 테스트 추가
olivejua Aug 20, 2024
c0d6ee3
refactor: TaskUpdate API 테스트 및 실패케이스 추가
olivejua Aug 21, 2024
ac12666
style: todo 주석 제거
olivejua Aug 21, 2024
d34dbc4
test: update task 실패케이스 추가
olivejua Aug 21, 2024
f2a372e
docs: task.adoc 생성
olivejua Aug 21, 2024
90a9de0
style: TODO 코멘트 수정 및 이슈 번호 추가
olivejua Sep 2, 2024
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
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,25 @@

import com.taskbuddy.api.controller.response.ApiResponse;
import com.taskbuddy.api.controller.response.ErrorDetail;
import com.taskbuddy.api.error.NotFoundResourceException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class ApiControllerAdvice {

@ExceptionHandler(NotFoundResourceException.class)
public ResponseEntity<ApiResponse<?>> handleNotFoundResourceException(NotFoundResourceException exception) {
return ResponseEntity.badRequest()
.body(ApiResponse.fail(new ErrorDetail(exception.getCode(), exception.getMessage())));
@ExceptionHandler(IllegalStateException.class)
public ResponseEntity<ApiResponse<?>> handleIllegalStateException(IllegalStateException exception) {
return ResponseEntity
.status(HttpStatus.BAD_REQUEST)
.body(ApiResponse.fail(new ErrorDetail("INVALID_PARAMETER_STATE", exception.getMessage())));
}

@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<ApiResponse<?>> handleIllegalArgumentException(IllegalArgumentException exception) {
return ResponseEntity
.status(HttpStatus.BAD_REQUEST)
.body(ApiResponse.fail(new ErrorDetail("INVALID_PARAMETER_STATE", exception.getMessage())));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
import com.taskbuddy.api.controller.response.ApiResponse;
import com.taskbuddy.api.controller.response.task.TaskResponse;
import com.taskbuddy.api.controller.response.task.TimeFrame;
import com.taskbuddy.api.error.NotFoundResourceException;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
Expand All @@ -16,13 +15,14 @@
@RequestMapping("/v1/tasks")
@RestController
public class TaskController {

// TODO spring boot validation 추가가 낫겠다. 일단 던지는 Exception에 대헤서 처리하고, Validation 도입하면 같이 붙여야지
@GetMapping("/{id}")
ResponseEntity<ApiResponse<TaskResponse>> getTask(@PathVariable("id") Long id) {
Assert.state(id >= 0, "The id value must be positive.");

// FIXME 서비스 로직 구현하면 제거하기 / Custom Exception 구현하기
if (id == 0) {
throw new NotFoundResourceException("NOT_FOUND_TASK", "Task를 찾을 수 없습니다.");
throw new IllegalArgumentException("The given task with id does not exist");
}

//Dummy
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,9 @@
import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName;
import static org.springframework.restdocs.request.RequestDocumentation.pathParameters;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

//TODO IntegrationTest와 UnitTest가 모였을 때 Fast 태그로 나누자
olivejua marked this conversation as resolved.
Show resolved Hide resolved
@SpringBootTest
@ExtendWith({RestDocumentationExtension.class})
public class TestControllerTest {
Expand All @@ -58,14 +58,14 @@ void setup(WebApplicationContext webApplicationContext, RestDocumentationContext
void 사용자는_Task_정보를_조회할_수_있다() throws Exception {
mockMvc.perform(RestDocumentationRequestBuilders.get("/v1/tasks/{id}", 1L)
.accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("$.status").value(ResultStatus.SUCCESS.name()))
.andExpect(jsonPath("$.data.id", allOf(notNullValue(), greaterThan(0))))
.andExpect(jsonPath("$.data.title").exists())
.andExpect(jsonPath("$.data.isDone").exists())
.andExpect(jsonPath("$.data.timeFrame").exists())
.andDo(print())
.andDo(document("get-a-task-with-id",
.andDo(document("get-a-task-with-id/success",
requestHeaders(
headerWithName(HttpHeaders.ACCEPT).description("accept header")
),
Expand All @@ -88,31 +88,33 @@ void setup(WebApplicationContext webApplicationContext, RestDocumentationContext
}

@Test
void 조회할_Task가_존재하지_않는다면_실패응답메시지를_받는다() throws Exception {
void 조회할_Task가_존재하지_않는다면_실패응답을_받는다() throws Exception {
mockMvc.perform(RestDocumentationRequestBuilders.get("/v1/tasks/{id}", 0)
Copy link
Collaborator

Choose a reason for hiding this comment

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

mockMvctestRestTemplate

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Tomcat Server에 대해서 잘 모르는것 같아 우선 정리하고, 두가지의 차이점을 알아본다음에 필요한 경우 수정해보겠습니다!
우선 PR이 오래 살아있는 것 같아 나누어서 다음 PR로 나누어서 올리겠습니다 😀

.accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isBadRequest())
.andExpect(header().string(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE))
.andExpect(jsonPath("$.status").value(ResultStatus.FAIL.name()))
.andExpect(jsonPath("$.data").doesNotExist())
.andExpect(jsonPath("$.error.code").value("NOT_FOUND_TASK"))
.andExpect(jsonPath("$.error").exists())
.andExpect(jsonPath("$.error.code").value("INVALID_PARAMETER_STATE"))
.andExpect(jsonPath("$.error.message").value("Task를 찾을 수 없습니다."))
.andDo(document("get-a-task-with-id/fail/does-not-exist"));
}

@Test
void ID가_음수값이면_실패응답을_받는다() throws Exception {
mockMvc.perform(RestDocumentationRequestBuilders.get("/v1/tasks/{id}", -1)
.accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andDo(document("failed-to-get-a-task-with-id",
requestHeaders(
headerWithName(HttpHeaders.ACCEPT).description("accept header")
),
pathParameters(
parameterWithName("id").description("task id")
),
responseHeaders(
headerWithName(HttpHeaders.CONTENT_TYPE).description("응답 헤더")
),
responseFields(
fieldWithPath("status").type(JsonFieldType.STRING).description("성공 여부"),
fieldWithPath("error").type(JsonFieldType.OBJECT).description("에러 상세정보"),
fieldWithPath("error.code").type(JsonFieldType.STRING).description("에러 코드"),
fieldWithPath("error.message").type(JsonFieldType.STRING).description("에러 메시지")
)));
.andExpect(status().isBadRequest())
.andExpect(header().string(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE))
.andExpect(jsonPath("$.status").value(ResultStatus.FAIL.name()))
.andExpect(jsonPath("$.data").doesNotExist())
.andExpect(jsonPath("$.error").exists())
.andExpect(jsonPath("$.error.code").value("INVALID_PARAMETER_STATE"))
.andExpect(jsonPath("$.error.message").value("The id value must be positive."))
.andDo(document("get-a-task-with-id/fail/negative-id-value"));
}

@Test
Expand All @@ -129,11 +131,11 @@ void setup(WebApplicationContext webApplicationContext, RestDocumentationContext
.accept(MediaType.APPLICATION_JSON)
.characterEncoding(StandardCharsets.UTF_8)
.content(objectMapper.writeValueAsString(request)))
.andDo(print())
.andExpect(status().isCreated())
.andExpect(jsonPath("$.status").value(ResultStatus.SUCCESS.name()))
.andExpect(jsonPath("$.data").doesNotExist())
.andDo(print())
.andDo(document("create-a-task",
.andDo(document("create-a-task/success",
requestHeaders(
headerWithName(HttpHeaders.ACCEPT).description("accept header"),
headerWithName(HttpHeaders.CONTENT_TYPE).description("content type header")
Expand Down Expand Up @@ -171,7 +173,7 @@ void setup(WebApplicationContext webApplicationContext, RestDocumentationContext
.andExpect(jsonPath("$.status").value(ResultStatus.SUCCESS.name()))
.andExpect(jsonPath("$.data").doesNotExist())
.andDo(print())
.andDo(document("update-a-task",
.andDo(document("update-a-task/success",
pathParameters(
parameterWithName("id").description("task id")
),
Expand Down Expand Up @@ -201,7 +203,7 @@ void setup(WebApplicationContext webApplicationContext, RestDocumentationContext
.andExpect(jsonPath("$.status").value(ResultStatus.SUCCESS.name()))
.andExpect(jsonPath("$.data").doesNotExist())
.andDo(print())
.andDo(document("remove-a-task",
.andDo(document("remove-a-task/success",
pathParameters(
parameterWithName("id").description("task id")
),
Expand Down