Home > Net >  Mock RestTemplate return null
Mock RestTemplate return null

Time:12-08

I need to mock restTemplate for a simple request:

HttpEntity<RequestVO> request = new HttpEntity<>(new RequestVO(),new HttpHeaders());
restTemplate.postForEntity("URL", request , ResponseVO.class);

But I'm getting null on postForEntity request:

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);

Tried to follow similar solution, I'm mocking relevant objects:

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

EDIT Same null results when tried similar tries as @JoãoDias suggested

when(restTemplate.postForEntity(anyString(), any(HttpEntity.class), eq(ResponseVO.class))).thenReturn(resp);

CodePudding user response:

Succeeded with 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 actually works by intercepting the HTTP API calls using a MockClientHttpRequestFactory. Based on our configuration, it creates a list of expected requests and corresponding responses. When the RestTemplate instance calls the API, it looks up the request in its list of expectations, and returns the corresponding response.

  • Related