我需要為一個簡單的請求模擬 restTemplate:
HttpEntity<RequestVO> request = new HttpEntity<>(new RequestVO(),new HttpHeaders());
restTemplate.postForEntity("URL", request , ResponseVO.class);
但我根據postForEntity要求得到空值:
ResponseVO respVO = new ResponseVO();
respVO.setEntry("https://www.test.com");
ResponseEntity<Object> resp =new ResponseEntity<>(
respVO,
HttpStatus.OK
);
when(restTemplate.postForEntity(any(), any(), any())).thenReturn(resp);
試圖遵循類似的解決方案,我在嘲笑相關物件:
@Mock
HttpHeaders httpHeaders;
@Mock
ResponseEntity responseEntity;
@Mock
private RestTemplate restTemplate;
編輯null嘗試與@Jo?oDias 建議的類似嘗試時的結果相同
when(restTemplate.postForEntity(anyString(), any(HttpEntity.class), eq(ResponseVO.class))).thenReturn(resp);
uj5u.com熱心網友回復:
成功使用MockRestServiceServer:
@Autowired
private RestTemplate restTemplate;
private MockRestServiceServer mockServer;
@BeforeClass
public void initMocks() {
mockServer = MockRestServiceServer.createServer(restTemplate);
}
...
mockServer.expect(ExpectedCount.once(),
requestTo(new URI("URL")))
.andExpect(method(HttpMethod.POST))
.andRespond(withStatus(HttpStatus.OK)
.contentType(MediaType.APPLICATION_JSON)
.body("EXPECTED")
MockRestServiceServer 實際上是通過使用 MockClientHttpRequestFactory 攔截 HTTP API 呼叫來作業的。根據我們的配置,它會創建一個預期請求和相應回應的串列。當 RestTemplate 實體呼叫 API 時,它會在其期望串列中查找請求,并回傳相應的回應。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/376000.html
標籤:春天 莫基托 弹簧测试 spring-resttemplate
上一篇:如何將檔案的完整路徑添加到視圖?
