Skip to content

Commit

Permalink
Merge branch 'dev/be' into refactor/767-template-controller-test-mock
Browse files Browse the repository at this point in the history
  • Loading branch information
jminkkk authored Oct 16, 2024
2 parents 2786597 + 9078171 commit 7026075
Show file tree
Hide file tree
Showing 6 changed files with 84 additions and 16 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ProblemDetail;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.lang.Nullable;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
Expand All @@ -16,6 +18,9 @@
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonMappingException.Reference;

import lombok.extern.slf4j.Slf4j;

@Slf4j
Expand All @@ -24,6 +29,7 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

private static final String PROPERTY_ERROR_CODE = "errorCode";
private static final String PROPERTY_TIMESTAMP = "timestamp";
private static final String DEFAULT_DETAIL_MASSAGE = "디테일 값이 존재하지 않습니다.";

@ExceptionHandler
public ResponseEntity<ProblemDetail> handleCodeZapException(CodeZapException codeZapException) {
Expand All @@ -50,6 +56,23 @@ protected ResponseEntity<Object> handleMethodArgumentNotValid(
.body(codeZapException.toProblemDetail());
}

@Override
protected ResponseEntity<Object> handleHttpMessageNotReadable(
HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) {
String exceptionMessage = "잘못된 JSON 형식입니다.";
if (ex.getCause() instanceof JsonMappingException jsonMappingException) {
exceptionMessage = jsonMappingException.getPath().stream()
.map(Reference::getFieldName)
.collect(Collectors.joining(" ")) + " 필드의 형식이 잘못되었습니다.";
}

CodeZapException codeZapException =
new CodeZapException(ErrorCode.INVALID_REQUEST, String.join("\n", exceptionMessage));

return ResponseEntity.status(codeZapException.getErrorCode().getHttpStatus())
.body(codeZapException.toProblemDetail());
}

@ExceptionHandler
public ResponseEntity<ProblemDetail> handleException(Exception exception) {
log.error("[Exception] 예상치 못한 오류 {} 가 발생했습니다.", exception.getClass().getName(), exception);
Expand All @@ -63,17 +86,18 @@ public ResponseEntity<ProblemDetail> handleException(Exception exception) {
protected ResponseEntity<Object> createResponseEntity(
@Nullable Object body, HttpHeaders headers, HttpStatusCode statusCode, WebRequest request
) {
ProblemDetail problemDetail = ProblemDetail.forStatus(statusCode);
if (body instanceof Exception) {
problemDetail.setDetail(((Exception) body).getMessage());
if (body instanceof ProblemDetail) {
return ResponseEntity.status(statusCode)
.body(setProperties((ProblemDetail) body, ErrorCode.SPRING_GLOBAL_EXCEPTION.getCode()));
}
ProblemDetail problemDetail = ProblemDetail.forStatusAndDetail(statusCode, DEFAULT_DETAIL_MASSAGE);
return ResponseEntity.status(statusCode)
.body(setProperties(problemDetail, ErrorCode.SPRING_GLOBAL_EXCEPTION.getCode()));
}

public static ProblemDetail setProperties(ProblemDetail problemDetail, int code) {
problemDetail.setProperty(PROPERTY_ERROR_CODE, code);
problemDetail.setProperty(PROPERTY_TIMESTAMP, LocalDateTime.now());
problemDetail.setProperty(PROPERTY_TIMESTAMP, LocalDateTime.now().toString());

return problemDetail;
}
Expand Down
8 changes: 4 additions & 4 deletions backend/src/main/resources/logger/file/error-appender.xml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<included>
<appender name="error-appender" class="ch.qos.logback.core.rolling.RollingFileAppender">

<file>${LOG_FILE_PATH}/${DATE_FORMAT}/error.log</file>
<file>${LOG_FILE_PATH}/error.log</file>

<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
Expand All @@ -15,9 +15,9 @@
<pattern>[%boldRed(%level)][%d{MM-dd HH:mm:ss}][%magenta(%8X{correlationId})][%boldRed(%replace(%logger{20}){'\\w\\.', ''}:%line)] %msg %n</pattern>
</encoder>

<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOG_FILE_PATH}/%d{yyyy-MM-dd}/error/error%i.log</fileNamePattern>
<maxFileSize>50MB</maxFileSize>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${LOG_FILE_PATH}/%d{yyyy-MM-dd}/error.log</fileNamePattern>
<totalSizeCap>5GB</totalSizeCap>
<maxHistory>30</maxHistory>
</rollingPolicy>

Expand Down
8 changes: 4 additions & 4 deletions backend/src/main/resources/logger/file/info-appender.xml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<included>
<appender name="info-appender" class="ch.qos.logback.core.rolling.RollingFileAppender">

<file>${LOG_FILE_PATH}/${DATE_FORMAT}/info.log</file>
<file>${LOG_FILE_PATH}/info.log</file>

<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>INFO</level>
Expand All @@ -15,9 +15,9 @@
<pattern>[%cyan(%level)][%d{MM-dd HH:mm:ss}][%magenta(%8X{correlationId})][%blue(%replace(%logger{20}){'\\w\\.', ''})] %msg %n</pattern>
</encoder>

<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOG_FILE_PATH}/%d{yyyy-MM-dd}/info/info%i.log</fileNamePattern>
<maxFileSize>50MB</maxFileSize>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${LOG_FILE_PATH}/%d{yyyy-MM-dd}/info.log</fileNamePattern>
<totalSizeCap>5GB</totalSizeCap>
<maxHistory>30</maxHistory>
</rollingPolicy>

Expand Down
8 changes: 4 additions & 4 deletions backend/src/main/resources/logger/file/warn-appender.xml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<included>
<appender name="warn-appender" class="ch.qos.logback.core.rolling.RollingFileAppender">

<file>${LOG_FILE_PATH}/${DATE_FORMAT}/warn.log</file>
<file>${LOG_FILE_PATH}/warn.log</file>

<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>WARN</level>
Expand All @@ -15,9 +15,9 @@
<pattern>[%red(%level)][%d{MM-dd HH:mm:ss}][%magenta(%8X{correlationId})][%red(%replace(%logger{20}){'\\w\\.', ''}:%line)] %msg %n</pattern>
</encoder>

<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOG_FILE_PATH}/%d{yyyy-MM-dd}/warn/warn%i.log</fileNamePattern>
<maxFileSize>50MB</maxFileSize>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${LOG_FILE_PATH}/%d{yyyy-MM-dd}/warn.log</fileNamePattern>
<totalSizeCap>5GB</totalSizeCap>
<maxHistory>30</maxHistory>
</rollingPolicy>

Expand Down
4 changes: 4 additions & 0 deletions backend/src/test/java/codezap/global/MockMvcTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import codezap.member.fixture.MemberFixture;
import codezap.member.service.MemberService;
import codezap.template.service.facade.TemplateApplicationService;
import codezap.tag.service.TagService;

@WebMvcTest(SpringExtension.class)
@EnableConfigurationProperties(CorsProperties.class)
Expand All @@ -43,6 +44,9 @@ public abstract class MockMvcTest {
@MockBean
protected MemberService memberService;

@MockBean
protected TagService tagService;

@MockBean
protected TemplateApplicationService templateApplicationService;

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package codezap.tag.controller;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import java.util.List;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.Import;

import codezap.global.MockMvcTest;
import codezap.tag.domain.Tag;
import codezap.tag.dto.response.FindAllTagsResponse;
import codezap.tag.dto.response.FindTagResponse;

@Import(TagController.class)
class TagControllerTest extends MockMvcTest {

@Test
@DisplayName("모든 태그 조회 성공")
void getTags() throws Exception {
// given
FindAllTagsResponse findAllTagsResponse = new FindAllTagsResponse(List.of(
FindTagResponse.from(new Tag(1L, "tag1")),
FindTagResponse.from(new Tag(2L, "tag2"))
));

when(tagService.findAllByMemberId(any())).thenReturn(findAllTagsResponse);

// when & then
mvc.perform(get("/tags")
.param("memberId", "1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.tags.size()").value(2));
}
}

0 comments on commit 7026075

Please sign in to comment.