簡體   English   中英

使用多部分請求測試 MockRestServiceServer spring-test

[英]Testing MockRestServiceServer spring-test with multipart request

最近我開始使用 Spring 的MockRestServiceServer在測試中驗證我的基於RestTemplate的請求。

當它用於簡單的獲取/發布請求時 - 一切都很好,但是,我無法弄清楚如何將它與 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 版本

非常感謝代碼片段:)

非常感謝提前

更新:根據 James 的要求,我添加了非工作測試片段(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,我不知道如何指定這些預期值

我認為這取決於您想要測試表單數據的深度。 一種方法,它不是 100% 完成,但對於單元測試(通常)來說“足夠好”是執行以下操作:

server.expect(once(), requestTo(getURI()))
       .andExpect(method(HttpMethod.POST))
        .andExpect(content().string(StringContains.containsString('paramname=Value') ))....

這是丑陋且不完整的,但有時很有用。 當然,您也可以將表單設置為自己的方法,然后使用模擬來嘗試驗證預期的參數是否全部到位。

多部分請求期望已添加到 Spring 5.3 中的MockRestServiceServer - 請參閱:

你可以使用

將主體解析為多部分數據並斷言它包含來自給定 MultiValueMap 的值。 值可能是以下類型:

  • 字符串 - 表單域
  • 資源 - 來自文件的內容
  • byte[] - 其他原始內容

multipartData(MultiValueMap) 的變體,其作用相同,但僅適用於實際值的一個子集。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM