代码之家  ›  专栏  ›  技术社区  ›  Ori Marko

Mock RestTemplate返回null

  •  0
  • Ori Marko  · 技术社区  · 3 年前

    我需要为一个简单的请求模拟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);
    

    试图跟随 similar solution ,我在嘲笑相关对象:

    @Mock
    HttpHeaders httpHeaders;
    @Mock
    ResponseEntity responseEntity;
    @Mock   
    private RestTemplate restTemplate;
    

    编辑 相同的 null 尝试与@JooDias建议的类似尝试时的结果

    when(restTemplate.postForEntity(anyString(), any(HttpEntity.class), eq(ResponseVO.class))).thenReturn(resp);
    
    0 回复  |  直到 3 年前
        1
  •  0
  •   Ori Marko    3 年前

    成功,使用 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时,它在期望列表中查找请求,并返回相应的响应。

    推荐文章