본문 바로가기
자바

mockMvc에서 HttpServletRequest 값 넣는 방법

by Hyeongjun_Ham 2024. 12. 3.

상황

- 컨트롤러 테스트임

- 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이 안나오게 처리할 수 있었다.