상황
- 컨트롤러 테스트임
- mock 테스트로 session은 잘 넣을 수 있으나 HttpServletRequest 을 넣으려고하니 안 들어감
대충 코드는 이렇다.
@GetMapping("/~~")
public void someMethod(@Valid SomeVo someVo, @PathVariable("lang") @NotBlank String lang, HttpServletRequest req, HttpServletResponse res) throws Exception {
// ...
//public static final 로 선언한 자료구조
SOME_MAP.remove(req.getRequestedSessionId());
}
req.getRequestedSessionId()에서 null이 입력되어 테스트 실패를 하는 상황이다.
여러가지 방법을 써 봤는데,
1. 직접 mockHttpServletRequest를 넣어보려고 하니 안 됨.
2. mockHttpServletRequest를 만들고 getSession()으로 mockSession을 뽑아내서 집어넣음 -> 안됨
등등.. 많은 시도를 했는데 다음 방법이 됐다.
ResultActions resultActions = mockMvc.perform(get(url)
//...
.with(mockHttpServletRequest -> {
mockHttpServletRequest.setRequestedSessionId(sessionId); // 요청에 세션 ID 설정
return mockHttpServletRequest;
})
);
.with() 메서드와 람다식을 사용해서 해당 파라미터에 set으로 넘겨주어 필요한 값에서 null이 안나오게 처리할 수 있었다.
'자바' 카테고리의 다른 글
ClientAbortException 시 HttpServletResponse 에서 .getOutputStream() 관리 (0) | 2024.12.05 |
---|---|
파일 다운로드 try catch 시 자원 반납, exception 시 json 응답 (0) | 2024.12.04 |
[스프링] .properties 에 값이 없는 경우 @Value 기본 값 설정 (0) | 2024.02.19 |
[JDBC] DB PK변경 방법 (0) | 2024.02.07 |
스프링 테스트 코드 @RestControllerAdvice를 거치게 하는 방법 (0) | 2024.01.25 |