我有一个像这样的控制器:
@RestController
@RequestMapping('/v1/document')
class DocumentV1Controller {
@PutMapping
HttpEntity<Document> newdoc(
@RequestHeader Map<String, String> headers, @RequestParam('document') MultipartFile multipartFile) {
}
}
我想使用Spring MVC Test和Spock测试它,但我无法弄清楚如何构建一个MockMultipartHttpServletRequestBuilder
将HttpMethod从POST更改为PUT请求。
这是Spock规范:
class DocumentV1ControllerSpec extends BaseControllerSpec {
Should 'test and document good request on /v1/document endpoint'() {
given:
File file = new File('./src/test/resources/demoC.csv')
MockMultipartFile multipartFile = new MockMultipartFile('file',file.getBytes())
when:
ResultActions result = mockMvc.perform(fileUpload('/v1/document')
.file(multipartFile))
then:
result.andExpect(status().isCreated())
}
}
我得到的错误是:
java.lang.AssertionError: Status expected:<201> but was:<405>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:60)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:89)
at org.springframework.test.web.servlet.result.StatusResultMatchers$10.match(StatusResultMatchers.java:664)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:171)
at gus.rest.api.v1.DocumentV1ControllerSpec.test and document good request on /v1/document endpoint(DocumentV1ControllerSpec.groovy:61)
我该怎么做才能让它发挥作用?
答案 0 :(得分:0)
我不是spock方面的专家,但是现在不推荐使用Spring {5. *版本)使用方法fileUpload
。
有一种方法可以将MockMultipartHttpServletRequestBuilder的默认POST方法更改为PUT:
class DocumentV1ControllerSpec extends BaseControllerSpec {
Should 'test and document good request on /v1/document endpoint'() {
given:
File file = new File('./src/test/resources/demoC.csv')
MockMultipartFile multipartFile = new MockMultipartFile('file', file.getBytes())
MockMultipartHttpServletRequestBuilder multipart = (MockMultipartHttpServletRequestBuilder) multipart('/v1/document').with(request -> {
request.setMethod(HttpMethod.PUT);
return request;
});
when:
ResultActions result = mockMvc.perform(multipart
.file(multipartFile))
then:
result.andExpect(status().isCreated())
}
}
诀窍是使用with(RequestPostProcessor postProcessor)
修改请求并为其设置方法PUT。