복붙노트

[SPRING] MockMVC를 통한 폼 포스트 테스트

SPRING

MockMVC를 통한 폼 포스트 테스트

API에 일반 폼 게시를 할 수 있는지 확인하기 위해 테스트를 작성하고 있습니다.

또한 꽤 많은 디버깅을 추가했지만 실제 양식에 의해 게시 된 데이터에 주목했습니다. (Postman / AngularJS 또는 w / e) 다음과 같은 mockMVC 테스트와 다릅니다.

MvcResult response = mockMvc
            .perform(post("/some/super/secret/url") //
                    .param("someparam1", "somevalue") //
                    .param("someparam2", "somevalue") //                
                    .contentType(MediaType.APPLICATION_FORM_URLENCODED) //
                    .accept(MediaType.APPLICATION_JSON)) //
            .andExpect(status().isOk()) //
            .andReturn();

설정은 실제 운영중인 설정과 동일합니다. 그러나 나의 인터셉터가 실제 테스트 (mockMVC가 아닌)에서 컨텐츠를 로깅 할 때 "someparam1 = somevalue & etc = encore"와 같은 형식으로 컨텐츠가 작성됩니다.

실제로 내용이없는 것처럼 보이는 mockMVC 내용을 인쇄 할 때 요청에 Params가 있지만 GET 매개 변수처럼 추가되었다고 가정합니다.

누구나 제대로 테스트하는 방법을 알고 있습니까? 서블릿 컨텍스트에 FormHttpMessageConverter를 추가 했음에도 불구하고 폼 포스트가 Spring에 의해 파싱되지 않는 것 같아서이 문제가 발생했습니다.

해결법

  1. ==============================

    1.classpath에 Apache HTTPComponents HttpClient가 있으면 다음과 같이 할 수 있습니다.

    classpath에 Apache HTTPComponents HttpClient가 있으면 다음과 같이 할 수 있습니다.

        mockMvc.perform(post("/some/super/secret/url")
                .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                .content(EntityUtils.toString(new UrlEncodedFormEntity(Arrays.asList(
                        new BasicNameValuePair("someparam1", "true"),
                        new BasicNameValuePair("someparam2", "test")
                )))));
    

    HttpClient가 없으면 urlencoded 폼 엔티티를 생성하는 간단한 도우미 메소드를 사용하여이를 수행 할 수 있습니다.

        mockMvc.perform(post("/some/super/secret/url")
                .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                .content(buildUrlEncodedFormEntity(
             "someparam1", "value1", 
             "someparam2", "value2"
        ))));
    

    이 헬퍼 함수로 :

    private String buildUrlEncodedFormEntity(String... params) {
        if( (params.length % 2) > 0 ) {
           throw new IllegalArgumentException("Need to give an even number of parameters");
        }
        StringBuilder result = new StringBuilder();
        for (int i=0; i<params.length; i+=2) {
            if( i > 0 ) {
                result.append('&');
            }
            try {
                result.
                append(URLEncoder.encode(params[i], StandardCharsets.UTF_8.name())).
                append('=').
                append(URLEncoder.encode(params[i+1], StandardCharsets.UTF_8.name()));
            }
            catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
        }
        return result.toString();
     }
    
  2. ==============================

    2.내가 만든이 작은 라이브러리 (https://github.com/f-lopes/spring-mvc-test-utils/)를 사용할 수도 있습니다.

    내가 만든이 작은 라이브러리 (https://github.com/f-lopes/spring-mvc-test-utils/)를 사용할 수도 있습니다.

    pom.xml에 종속성 추가 :

    <dependency>
        <groupId>io.florianlopes</groupId>
        <artifactId>spring-mvc-test-utils</artifactId>
        <version>1.0.1</version>
        <scope>test</scope>
    </dependency>
    

    MockMvc와 함께 사용 :

    mockMvc.perform(MockMvcRequestBuilderUtils.postForm("/users", new AddUserForm("John", "Doe", null, new Address(1, "Street", 5222, "New York"))))
        .andExpect(MockMvcResultMatchers.status().isFound())
        .andExpect(MockMvcResultMatchers.redirectedUrl("/users"))
        .andExpect(MockMvcResultMatchers.flash().attribute("message", "success"));
    

    이 라이브러리는 폼 객체에 따라 MockMvc 요청에 매개 변수를 추가하기 만합니다.

    다음은 내가 작성한 상세한 자습서입니다. https://blog.florianlopes.io/tool-for-spring-mockmvcrequestbuilder-forms-tests/

  3. from https://stackoverflow.com/questions/36568518/testing-form-posts-through-mockmvc by cc-by-sa and MIT license