如何通过Kotlin DSL为MockMvc传递自定义请求头?
问题:Kotlin DSL下MockMvc如何传递自定义请求头?
我有一段可正常运行的MockMvc代码:
val headers = HttpHeaders() headers.add("Content-Type", "application/merge-patch+json") mockMvc.perform( patch(path) .headers(headers) .content(objectMapper.writeValueAsString(patchRequest)), ).andExpect(status().isOk) .andReturn()
现在想用Kotlin DSL重写,目前写了这些,但不知道怎么传递自定义请求头:
val result = mockMvc.patch(path) { //this.header = headers content = objectMapper.writeValueAsString(patchRequest) }.andExpect{ status { isOk() } } .andReturn()
解决方案
方法1:直接添加单个请求头
在DSL代码块里使用header(key, value)方法逐个添加请求头:
val result = mockMvc.patch(path) { header("Content-Type", "application/merge-patch+json") content = objectMapper.writeValueAsString(patchRequest) }.andExpect{ status { isOk() } } .andReturn()
方法2:传入已构建的HttpHeaders对象
如果已经有现成的HttpHeaders实例,直接在DSL块里调用headers()方法传入即可:
val headers = HttpHeaders() headers.add("Content-Type", "application/merge-patch+json") // 可添加更多自定义请求头 headers.add("X-Custom-Header", "custom-value") val result = mockMvc.patch(path) { headers(headers) content = objectMapper.writeValueAsString(patchRequest) }.andExpect{ status { isOk() } } .andReturn()
方法3:DSL风格构建请求头
也可以直接在DSL块内用headers子块构建请求头:
val result = mockMvc.patch(path) { headers { add("Content-Type", "application/merge-patch+json") add("X-Custom-Header", "custom-value") } content = objectMapper.writeValueAsString(patchRequest) }.andExpect{ status { isOk() } } .andReturn()
内容的提问来源于stack exchange,提问作者gstackoverflow
相关产品推荐
相关产品推荐

