본문 바로가기

Spring Boot 실력 상승!

MockHttpServletRequestBuilder의 .param/.params

책 보면서 연습하다가 MockMvc에서 param을 쓰는 것을 발견했다.

@RunWith(SpringRunner.class)
@WebMvcTest(controllers = HelloController.class)
public class HelloControllerTest {

    @Autowired
    private MockMvc mvc;

    @Test
    public void hello() throws Exception {
        String hello = "hello";

        mvc.perform(get("/hello"))
                .andExpect(status().isOk())
                .andExpect(content().string(hello));
    }

    @Test
    public void returnHelloDto() throws Exception {
        String name = "name";
        int amount = 1000;

        mvc.perform(get("/hello/dto")
                .param("name", name)
                .param("amount", String.valueOf(amount)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.name", Matchers.is(name)))
                .andExpect(jsonPath("$.amount", Matchers.is(amount)));
    }
}

 

해당 코드를 쓰기 위해 자동완성을 했더니 params가 나왔다.

 

음.. 그럼 파라미터가 복수일 경우 그냥 params를 쓰면 되는게 아닐까? 굳이 param을 여러 개 쓸 필요가 있을까? 라는 생각이 들어서 params를 써보기로 했다.

MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("name", name);
params.add("amount", String.valueOf(amount));

mvc.perform(get("/hello/dto")
.params(params))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name", Matchers.is(name)))
.andExpect(jsonPath("$.amount", Matchers.is(amount)));

 

MultiValueMap을 선언 후 key, value 형태로 add. 그 후 params 메소드에 담아준다.

 

테스트 결과 요시!

 

근데 따지고 보면 param이나 params나 똑같이 처리된다.

 

둘다 결국엔 Map에 넣고 처리함.

 

 

결론: 개인적으로는 params로 처리하는게 더 깔끔하다고 생각하지만 귀찮으니 걍 param 쓰는것도 나쁘지 않을듯