ysk(0soo)
Lifealong
ysk(0soo)
전체 방문자
오늘
어제
  • 분류 전체보기 (238)
    • Java (50)
      • whiteship-java-study (11)
      • Java (28)
      • time (6)
    • Spring (68)
      • JPA (15)
      • Spring (1)
      • SpringBoot (1)
      • SpringMVC (6)
      • Spring Security (22)
      • Jdbc (1)
      • RestDocs (14)
      • log (6)
    • Kotlin (3)
    • Web (2)
      • nginx (1)
    • Database (14)
      • MySQL (5)
      • PostgreSQL (1)
      • SQL (1)
      • Redis (4)
    • C, C++ (0)
    • Git (1)
    • Docker (2)
    • Cloud (3)
      • AWS (3)
    • 도서, 강의 (0)
      • t5 (0)
    • 기타 (7)
      • 프로그래밍 (1)
    • 끄적끄적 (0)
    • CS (14)
      • 운영체제(OS) (2)
      • 자료구조(Data Structure) (9)
    • 하루한개 (12)
      • 우아한 테크코스-10분테코톡 (12)
    • 스터디 (12)
      • 클린 아키텍처- 로버트마틴 (2)
      • JPA 프로그래밍 스터디 (10)
    • 테스트 (34)
      • JUnit (19)
      • nGrinder (2)
      • JMeter (0)
    • Infra (3)
    • 프로그래머스 백엔드 데브코스 3기 (0)
    • 디자인 패턴 (3)
    • Issue (4)
    • system (1)
      • grafana (0)
      • Prometheus (0)

블로그 메뉴

  • 홈
  • 태그
  • 방명록
  • github

공지사항

인기 글

태그

  • java
  • tree
  • LocalDateTime
  • junit5
  • StructuredConcorrency
  • FilterSecurityInterceptor
  • AuthenticationException
  • querydsl
  • AccessDecisionVoter 커스텀
  • mysql
  • 동등성
  • scope value
  • nGrinder
  • restdocs enum
  • DataJpaTest
  • AccessDecisionManager
  • jpa
  • nginx basic auth
  • 동시성 제어
  • 트랜잭션
  • restdocs custom
  • node exporter basic auth
  • 정규표현식
  • UserDetailsService
  • 가상 스레드
  • 인가(Authorization) 처리
  • 동일성
  • 구조화된 동시성
  • VirtualThread Springboot
  • 가상 스레드 예외 핸들링

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
ysk(0soo)

Lifealong

테스트/JUnit

MockMvc 테스트시 201 created URI를 검증하는 방법

2023. 1. 24. 23:46

현재 ItemController에서는 Resource 생성 시 201 created 응답과 함께 생성된 자원의 URI를 리턴해주고있다.

@RequestMapping("/api/v1/items")
@RestController
@RequiredArgsConstructor
public class ItemController {
​
  private final ItemFacadeService itemService;
​
  @PostMapping(consumes = APPLICATION_JSON_VALUE, produces = APPLICATION_JSON_VALUE)
  public ResponseEntity<URI> createItem(@RequestBody @Valid ItemCreateRequest itemCreateRequest) {
    Long itemId = itemService.createItem(itemCreateRequest);
​
    String createdURI = ServletUriComponentsBuilder.fromCurrentRequestUri().toUriString() + "/" + itemId; // 현재 요청이 들어온 URI
​
    return ResponseEntity.created(URI.create(createdURI)).build();
  }
}

ServletUriComponentsBuilder.fromCurrentRequestUri() : 현재 요청이 들어온 URI

MockMvc를 이용한 테스트시에 andDo(print()) 메서드로 다음의 헤더 응답정보가 있을 시에는

MockHttpServletResponse:
           Status = 201
    Error message = null
          Headers = [Location:"<http://localhost/api/v1/items/1>"]
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = <http://localhost/api/v1/items/1>
          Cookies = []

아래 두 방법을 사용하면 된다

1. header().string(key, value)

import org.hamcrest.Matchers.*;
​
mvc.perform(request)
  .andExpect(status().isCreated())
  .andExpect(header().string("Location", containsString("/resources/"+id)));

2. redirectUrlPattern()

import org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
​
private static final String BASE_REQUEST_URI = "/api/v1/items";
​
mvc.perform(request)
  .andExpect(status().isCreated())
  .andExpect(redirectedUrlPattern("http://*" + BASE_REQUEST_URI + "/" + returnId));
.andExpect(redirectedUrlPattern("http://*/the/resources"))

이 패턴은 모든 host 이름과 일치하므로 localhost 를 하드코딩할 필요가 없다 .
AntPathMatcher이다.
 SpringDoc - 여기에서 사용할 수 있는 다양한 패턴에 대해 자세히 알아볼 수 있다. .

저작자표시 비영리 (새창열림)

'테스트 > JUnit' 카테고리의 다른 글

@WebMvcTest Security 401 403 응답 해결방법 - csrf  (0) 2023.01.25
Mockito Verify, Mock Object 검증, 호출 횟수 검증  (0) 2023.01.25
MockMvc 테스트 body가 '<no character encoding set>' 인경우  (0) 2023.01.24
JUnit5 생성자 주입 방법과 원리  (0) 2022.12.16
Junit5 의존성 주입 에러@Autowired ParameterResolutionException 과 해결방법  (0) 2022.12.16
    '테스트/JUnit' 카테고리의 다른 글
    • @WebMvcTest Security 401 403 응답 해결방법 - csrf
    • Mockito Verify, Mock Object 검증, 호출 횟수 검증
    • MockMvc 테스트 body가 '<no character encoding set>' 인경우
    • JUnit5 생성자 주입 방법과 원리
    ysk(0soo)
    ysk(0soo)
    백엔드 개발을 좋아합니다. java kotlin spring, infra 에 관심이 많습니다. email : kim206gh@naver.com github : https://github.com/devysk

    티스토리툴바