【发布时间】:2017-05-23 08:05:58
【问题描述】:
最近我开始在测试中使用 Spring 的 MockRestServiceServer 来验证我的基于 RestTemplate 的请求。
当它用于简单的 get/post 请求时——一切都很好,但是,我不知道如何将它与 POST 多部分请求一起使用:
例如,我想测试的工作代码如下所示:
public ResponseEntity<String> doSomething(String someParam, MultipartFile
file, HttpHeaders headers) { //I add headers from request
MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
map.add("file", new ByteArrayResource(file.getBytes()) {
@Override
public String getFilename() {
return file.getOriginalFilename();
}
});
map.add("someParam", someParam);
HttpEntity<MultiValueMap<String, Object>> requestEntity = new
HttpEntity<>(map, headers);
return this.restTemplate.exchange(
getDestinationURI(),
HttpMethod.POST,
requestEntity,
String.class);
}
所以我的问题是如何使用org.springframework.test.web.client.MockRestServiceServer 指定我的期望?请注意,我不想只是用 mockito 或其他东西来模拟“交换”方法,而是更喜欢使用 MockRestServiceServer
我使用的是 spring-test-4.3.8.RELEASE 版本
非常感谢您提供代码 sn-p :)
提前非常感谢
更新: 根据詹姆斯的要求,我正在添加非工作测试 sn-p(Spock 测试):
MockRestServiceServer server = MockRestServiceServer.bindTo(restTemplate).build()
server.expect(once(), requestTo(getURI()))
.andExpect(method(HttpMethod.POST))
.andExpect(header(HttpHeaders.CONTENT_TYPE, startsWith("multipart/form-data;boundary=")))
.andExpect(content().formData(["someParam" : "SampleSomeParamValue", "file" : ???????] as MultiValueMap))
.andRespond(withSuccess("sample response", MediaType.APPLICATION_JSON))
multipartFile.getBytes() >> "samplefile".getBytes()
multipartFile.getOriginalFilename() >> "sample.txt"
我在声明请求内容时遇到异常。表单数据不同,因为实际表单数据是在内部使用每个参数的 Content-Disposition、Content-Type、Content-Length 创建的,我不知道如何指定这些预期值
【问题讨论】:
-
你能加你POST测试sn-ps吗?
-
感谢您的评论,添加了指定期望的无效尝试
-
运气好吗?我正在尝试做类似的事情并面临问题。
-
很遗憾没有。看起来这种模拟技术只适合直接“REST”操作。多部分声音“超出”这些简单操作的集合。我暂时放弃了这个
标签: java spring multipartform-data spring-test