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

Feat/#33 Project API #37

Merged
merged 6 commits into from
Aug 13, 2024
Merged
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package info.logbat.common.payload;

import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.springframework.http.HttpStatus;

@Getter
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ApiCommonResponse<T> {

private int statusCode;
private String message;
private T data;

private ApiCommonResponse(int status, String message, T data) {
this.statusCode = status;
this.message = message;
this.data = data;
}

private ApiCommonResponse(int statusCode, String message) {
this.statusCode = statusCode;
this.message = message;
}

private ApiCommonResponse(int statusCode) {
this.statusCode = statusCode;
}

public static <T> ApiCommonResponse<T> createApiResponse(HttpStatus httpStatus, String message,
T data) {
return new ApiCommonResponse<>(httpStatus.value(), message, data);
}

public static ApiCommonResponse<Void> createFailResponse(HttpStatus httpStatus,
String message) {
return new ApiCommonResponse<>(httpStatus.value(), message);
}
Copy link
Member

Choose a reason for hiding this comment

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

곡톡 μ—λŸ¬ ν•Έλ“€λŸ¬λ„ λ‚˜μ€‘μ— λ§Œλ“€μ–΄μš”


public static ApiCommonResponse<Void> createSuccessResponse() {
return new ApiCommonResponse<>(HttpStatus.OK.value());
}

public static <T> ApiCommonResponse<T> createSuccessResponse(T data) {
return new ApiCommonResponse<>(HttpStatus.OK.value(), "Success", data);
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package info.logbat.domain.project.application;

import info.logbat.domain.project.domain.Project;
import info.logbat.domain.project.presentation.payload.request.ProjectUpdateRequest;
import info.logbat.domain.project.presentation.payload.response.ProjectCommonResponse;
import info.logbat.domain.project.repository.ProjectJpaRepository;
import lombok.RequiredArgsConstructor;
Expand All @@ -27,9 +26,9 @@ public ProjectCommonResponse getProjectByName(String name) {
return ProjectCommonResponse.from(project);
}

public ProjectCommonResponse updateProjectValues(ProjectUpdateRequest request) {
Project project = getProject(request.id());
project.updateName(request.name());
public ProjectCommonResponse updateProjectValues(Long id, String name) {
Project project = getProject(id);
project.updateName(name);
return ProjectCommonResponse.from(project);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package info.logbat.domain.project.presentation;

import info.logbat.common.payload.ApiCommonResponse;
import info.logbat.domain.project.application.ProjectService;
import info.logbat.domain.project.presentation.payload.request.ProjectCreateRequest;
import info.logbat.domain.project.presentation.payload.request.ProjectUpdateRequest;
import info.logbat.domain.project.presentation.payload.response.ProjectCommonResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/v1/projects")
@RequiredArgsConstructor
public class ProjectController {

private final ProjectService projectService;

@GetMapping("/{name}")
public ApiCommonResponse<ProjectCommonResponse> get(@PathVariable String name) {
return ApiCommonResponse.createSuccessResponse(projectService.getProjectByName(name));
}

@PostMapping
public ResponseEntity<ApiCommonResponse<ProjectCommonResponse>> create(
@RequestBody ProjectCreateRequest request) {
ApiCommonResponse<ProjectCommonResponse> response = ApiCommonResponse.createApiResponse(
HttpStatus.CREATED, "Success", projectService.createProject(request.name()));
return ResponseEntity.status(HttpStatus.CREATED).body(response);
}
Comment on lines +32 to +38
Copy link
Member

Choose a reason for hiding this comment

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

λ‹¨μˆœν•œ statusλ₯Ό CREATED둜 μ„€μ •ν•˜λŠ” μž‘μ—…μ΄λΌλ©΄

  @ResponseStatus(HttpStatus.CREATED)

λ₯Ό μΆ”κ°€ν•˜λŠ” 방법은 μ–΄λ–¨κΉŒμš”?!!


@PutMapping("/{id}")
public ApiCommonResponse<ProjectCommonResponse> update(@PathVariable Long id,
@RequestBody ProjectUpdateRequest request) {
return ApiCommonResponse.createSuccessResponse(
projectService.updateProjectValues(id, request.name()));
}

@DeleteMapping("/{id}")
public ApiCommonResponse<Long> delete(@PathVariable Long id) {
Long expectedId = projectService.deleteProject(id);
return ApiCommonResponse.createSuccessResponse(expectedId);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package info.logbat.domain.project.presentation.payload.request;

public record ProjectCreateRequest(String name) {

}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
package info.logbat.domain.project.presentation.payload.request;

public record ProjectUpdateRequest(Long id, String name) {
public record ProjectUpdateRequest(String name) {

}
Original file line number Diff line number Diff line change
Expand Up @@ -3,33 +3,35 @@
import com.fasterxml.jackson.databind.ObjectMapper;
import info.logbat.domain.log.application.LogService;
import info.logbat.domain.log.presentation.LogController;
import info.logbat.domain.project.application.ProjectService;
import info.logbat.domain.project.presentation.ProjectController;
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.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.MockMvc;

/**
/*
* 이후 ν…ŒμŠ€νŠΈ ν•˜λ €λ©΄ Controller에 λŒ€ν•΄ controllers에 μΆ”κ°€ν•˜κ³ , ControllerTestSupportλ₯Ό 상속받아 ν…ŒμŠ€νŠΈλ₯Ό μ§„ν–‰ν•˜μ‹œλ©΄ λ©λ‹ˆλ‹€.
*/
@WebMvcTest(controllers = {
LogController.class
}
)
@WebMvcTest(controllers = {LogController.class, ProjectController.class})
@ActiveProfiles("test")
public abstract class ControllerTestSupport {

@Autowired
protected MockMvc mockMvc;
@Autowired
protected MockMvc mockMvc;

@Autowired
protected ObjectMapper objectMapper;
@Autowired
protected ObjectMapper objectMapper;

@MockBean
protected LogService logService;
@MockBean
protected LogService logService;

/**
* 이후 ν•„μš”ν•œ μ„œλΉ„μŠ€μ— λŒ€ν•΄ MockBean을 μΆ”κ°€ν•˜μ—¬ ν…ŒμŠ€νŠΈλ₯Ό μ§„ν–‰ν•˜μ‹œλ©΄ λ©λ‹ˆλ‹€.
*/
@MockBean
protected ProjectService projectService;

/*
* 이후 ν•„μš”ν•œ μ„œλΉ„μŠ€μ— λŒ€ν•΄ MockBean을 μΆ”κ°€ν•˜μ—¬ ν…ŒμŠ€νŠΈλ₯Ό μ§„ν–‰ν•˜μ‹œλ©΄ λ©λ‹ˆλ‹€.
*/

}
miiiinju1 marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
import static org.mockito.Mockito.spy;

import info.logbat.domain.project.domain.Project;
import info.logbat.domain.project.presentation.payload.request.ProjectUpdateRequest;
import info.logbat.domain.project.presentation.payload.response.ProjectCommonResponse;
import info.logbat.domain.project.repository.ProjectJpaRepository;
import java.time.LocalDateTime;
Expand Down Expand Up @@ -106,15 +105,14 @@ class whenUpdateProject {
void canUpdateProjectValues() {
// Arrange
LocalDateTime expectedUpdatedAt = LocalDateTime.now();
ProjectUpdateRequest request = new ProjectUpdateRequest(expectedProjectId,
expectedUpdatedProjectName);
given(projectRepository.findById(expectedProjectId)).willReturn(
Optional.of(expectedProject));
given(expectedProject.getId()).willReturn(expectedProjectId);
given(expectedProject.getCreatedAt()).willReturn(expectedCreatedAt);
given(expectedProject.getUpdatedAt()).willReturn(expectedUpdatedAt);
// Act
ProjectCommonResponse actualResult = projectService.updateProjectValues(request);
ProjectCommonResponse actualResult = projectService.updateProjectValues(
expectedProjectId, expectedUpdatedProjectName);
// Assert
assertThat(actualResult)
.extracting("id", "name", "createdAt", "updatedAt")
Expand All @@ -128,11 +126,10 @@ void canUpdateProjectValues() {
void cannotUpdateProjectValues() {
// Arrange
Long expectedWrongProjectId = 2L;
ProjectUpdateRequest request = new ProjectUpdateRequest(expectedWrongProjectId,
expectedUpdatedProjectName);
given(projectRepository.findById(expectedWrongProjectId)).willReturn(Optional.empty());
// Act & Assert
assertThatThrownBy(() -> projectService.updateProjectValues(request))
assertThatThrownBy(() -> projectService.updateProjectValues(expectedWrongProjectId,
expectedUpdatedProjectName))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("ν”„λ‘œμ νŠΈλ₯Ό 찾을 수 μ—†μŠ΅λ‹ˆλ‹€.");
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
package info.logbat.domain.project.presentation;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import info.logbat.domain.common.ControllerTestSupport;
import info.logbat.domain.project.presentation.payload.response.ProjectCommonResponse;
import java.time.LocalDateTime;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;

@ExtendWith(MockitoExtension.class)
@DisplayName("ProjectControllerλŠ”")
class ProjectControllerTest extends ControllerTestSupport {

private final Long expectedId = 1L;
private final String expectedName = "projectName";
private final ProjectCommonResponse projectCommonResponse = mock(ProjectCommonResponse.class);

@Nested
@DisplayName("GET /v1/projects/{name}에 λŒ€ν•΄")
class describeGet {

@Test
@DisplayName("ν”„λ‘œμ νŠΈ μ΄λ¦„μœΌλ‘œ ν”„λ‘œμ νŠΈλ₯Ό μ‘°νšŒν•  수 μžˆλ‹€.")
void willReturnProjectInformation() throws Exception {
// Arrange
LocalDateTime expectedCreatedAt = LocalDateTime.now();
given(projectService.getProjectByName("projectName")).willReturn(projectCommonResponse);
given(projectCommonResponse.id()).willReturn(expectedId);
given(projectCommonResponse.name()).willReturn(expectedName);
given(projectCommonResponse.createdAt()).willReturn(expectedCreatedAt);
// Act
MockHttpServletRequestBuilder get = get("/v1/projects/{name}", "projectName");
// Assert
mockMvc.perform(get)
.andExpect(status().isOk())
.andExpect(jsonPath("$.statusCode").value(200))
.andExpect(jsonPath("$.message").value("Success"))
.andExpect(jsonPath("$.data.id").value(expectedId))
.andExpect(jsonPath("$.data.name").value(expectedName))
.andExpect(jsonPath("$.data.createdAt").value(expectedCreatedAt.toString()))
.andExpect(jsonPath("$.data.updatedAt").doesNotExist());
}

}

@Nested
@DisplayName("POST /v1/projects에 λŒ€ν•΄")
class describePost {

@Test
@DisplayName("ν”„λ‘œμ νŠΈλ₯Ό 생성할 수 μžˆλ‹€.")
void willCreateProject() throws Exception {
// Arrange
LocalDateTime expectedCreatedAt = LocalDateTime.now();
given(projectService.createProject(expectedName)).willReturn(projectCommonResponse);
given(projectCommonResponse.id()).willReturn(expectedId);
given(projectCommonResponse.name()).willReturn(expectedName);
given(projectCommonResponse.createdAt()).willReturn(expectedCreatedAt);
// Act
MockHttpServletRequestBuilder post = post("/v1/projects")
.contentType("application/json")
.content("{\"name\":\"" + expectedName + "\"}");
// Assert
mockMvc.perform(post)
.andExpect(status().isCreated())
.andExpect(jsonPath("$.statusCode").value(201))
.andExpect(jsonPath("$.message").value("Success"))
.andExpect(jsonPath("$.data.id").value(expectedId))
.andExpect(jsonPath("$.data.name").value(expectedName))
.andExpect(jsonPath("$.data.createdAt").value(expectedCreatedAt.toString()))
.andExpect(jsonPath("$.data.updatedAt").doesNotExist());
}

}

@Nested
@DisplayName("PUT /v1/projects/{id}에 λŒ€ν•΄")
class describePut {

@Test
@DisplayName("ν”„λ‘œμ νŠΈλ₯Ό μˆ˜μ •ν•  수 μžˆλ‹€.")
void willUpdateProject() throws Exception {
// Arrange
LocalDateTime expectedCreatedAt = LocalDateTime.now();
given(projectService.updateProjectValues(expectedId, expectedName)).willReturn(
projectCommonResponse);
given(projectCommonResponse.id()).willReturn(expectedId);
given(projectCommonResponse.name()).willReturn(expectedName);
given(projectCommonResponse.createdAt()).willReturn(expectedCreatedAt);
// Act
MockHttpServletRequestBuilder put = put("/v1/projects/{id}", expectedId)
.contentType("application/json")
.content("{\"name\":\"" + expectedName + "\"}");
// Assert
mockMvc.perform(put)
.andExpect(status().isOk())
.andExpect(jsonPath("$.statusCode").value(200))
.andExpect(jsonPath("$.message").value("Success"))
.andExpect(jsonPath("$.data.id").value(expectedId))
.andExpect(jsonPath("$.data.name").value(expectedName))
.andExpect(jsonPath("$.data.createdAt").value(expectedCreatedAt.toString()))
.andExpect(jsonPath("$.data.updatedAt").doesNotExist());
}

}

@Nested
@DisplayName("DELETE /v1/projects/{id}에 λŒ€ν•΄")
class describeDelete {

@Test
@DisplayName("ν”„λ‘œμ νŠΈλ₯Ό μ‚­μ œν•  수 μžˆλ‹€.")
void willDeleteProject() throws Exception {
// Arrange
given(projectService.deleteProject(any(Long.class))).willReturn(expectedId);
// Act
MockHttpServletRequestBuilder delete = delete("/v1/projects/{id}", expectedId);
// Assert
mockMvc.perform(delete)
.andExpect(status().isOk())
.andExpect(jsonPath("$.statusCode").value(200))
.andExpect(jsonPath("$.message").value("Success"))
.andExpect(jsonPath("$.data").value(expectedId));
}

}

}
miiiinju1 marked this conversation as resolved.
Show resolved Hide resolved