1

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);
Ori Marko
  • 56,308
  • 23
  • 131
  • 233

1 Answers1

0

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.

Ori Marko
  • 56,308
  • 23
  • 131
  • 233
  • I have the same issue but I couldn't fix it. How can I fix it? Here is the link : https://stackoverflow.com/questions/76308882/spring-boot-junit-test-resttemplate-returns-null-in-servicetest – S.N May 22 '23 at 20:31