简体   繁体   中英

Java - How to test RestTemplate POST method success status code?

I am using RestTemplate postForEntity method to post to an endpoint. If POST is successful then it returns status code of 201 . I need help to write test case for this method using Mockito . Any suggestions are appreciated. Thank you

Here is my code

public int postJson(Set<String> last){
    try{

        LOGGER.info("Status code " + statusCode);
    }   catch (Exception e) {
        e.printStackTrace();
    }
    return statusCode;          
}
private HttpEntity getHttpEntity() {
    return new HttpEntity<>( null, getHttpHeaders() );
}

private HttpHeaders getHttpHeaders() {
    return headersBuilder.build();
}

There is a problem in your approach, you're confusing integration testing with unit testing here. If you want just to do unit test, then you can mock RestTemplate using @Mock. But if you want to verify the integration with some remote service and you're okay to verify this from controller by using @MockMvc, refer this answer .

You can mock the below code in your test cases , below is the sample code , you can use Mockito.any or Mockito.eq methods to mock the objects .

ResponseEntity<String> result = restTemplate.postForEntity(url, new HttpEntity<>( request, getHttpHeaders() ), String.class);

@RunWith(MockitoJUnitRunner.class)    
public class Test {
       @InjectMocks
    private TestController testController;

    @Mock
    private RestTemplate restTemplate;   
        public void testRest() {
        ResponseEntity<String> result = Mockito.mock(ResponseEntity.class);
        Mockito.when(restTemplate.postForEntity(Mockito.any(String.class), Mockito.eq(HttpEntity.class), Mockito.any(String.class))).thenReturn(result);

        }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM