最近,我开始使用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之类的"exchange“方法,而是更喜欢使用MockRestServiceServer
我使用的是spring 4.3.8 version版本
代码片段将是非常感激的:)
提前谢谢
Update:根据詹姆斯的请求,我添加了不工作的测试片段(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"在断言请求内容时,我会得到异常。表单数据是不同的,因为实际的表单数据是在内部创建的,内容配置、内容类型、每个参数的内容长度,我不知道如何指定这些预期值
发布于 2020-11-11 11:34:08
在Spring5.3中,多部分请求期望已添加到MockRestServiceServer中-请参见:
您可以使用
将主体解析为多部分数据,并断言它完全包含来自给定MultiValueMap的值。数值可分为以下类型:
content().multipartDataContains(Map expectedMap)multipartData(MultiValueMap)的变体,它只对实际值的子集执行相同的操作。
发布于 2017-12-22 20:46:59
我认为这取决于您希望对表单数据进行多深的测试。有一种方法,虽然不是100%完成,但对于单元测试来说“足够好”(通常)是这样做的:
server.expect(once(), requestTo(getURI()))
.andExpect(method(HttpMethod.POST))
.andExpect(content().string(StringContains.containsString('paramname=Value') ))....这是丑陋和不完整的,但有时是有用的。当然,您也可以工作使表单设置是它自己的方法,然后使用模拟来尝试验证预期的参数是否都已到位。
https://stackoverflow.com/questions/44129170
复制相似问题