Testing Form posts through MockMVC

前端 未结 3 914
悲&欢浪女
悲&欢浪女 2020-12-30 21:11

I\'m writing tests to verify that I can do a generic form post to our API.

I\'ve also added quite some debugging, but I noticed that the data posted by an actual for

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-30 21:45

    Here is a Kotlin SpringBoot example:

    @RunWith(MockitoJUnitRunner::class)
    class ApiFormControllerTest {
    
      lateinit var mvc: MockMvc
    
      @InjectMocks
      lateinit var apiFormController: ApiFormController
    
      @Before
      fun setup() {
        mvc = MockMvcBuilders.standaloneSetup(apiFormController).setControllerAdvice(ExceptionAdvice()).build()
      }
    
      fun MockHttpServletRequestBuilder.withForm(params: Map): MockHttpServletRequestBuilder {
        this.contentType(MediaType.APPLICATION_FORM_URLENCODED)
            .content(
                EntityUtils.toString(
                    UrlEncodedFormEntity(
                        params.entries.toList().map { BasicNameValuePair(it.key, it.value) }
                    )
                )
            )
        return this
      }
    
      @Test
      fun canSubmitValidForm() {
        mvc.perform(post("/forms").withForm(mapOf("subject" to "hello")))
            .andExpect(status().isOk)
      }
    
    }
    

提交回复
热议问题