Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write mockito junit for Resttemplate postForObject method

I am trying to post list of messages to the rest api. How to write mockito junit for the method postJSONData below:

public class PostDataService{

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    private Environment env;

    private HttpEntity<String> httpEntity;

    private HttpHeaders httpHeaders;

    private String resourceURL = null;

    public PostDataService(){
    httpHeaders = new HttpHeaders();
    httpHeaders.set("Content-Type", "application/json");
    }

    public void postJSONData(List<String> data){
    try
    {
    resourceURL = env.getProperty("baseURL") + env.getProperty("resourcePath");
    httpEntity = new HttpEntity<String>(data.toString(), httpHeaders);
    String response = restTemplate.postForObject(resourceURL, httpEntity, String.class);
    }
    catch (RestClientException e) {
            LOGGER.info("ErrorMessage::" + e.getMessage());
            LOGGER.info("ErrorCause::" + e.getCause());
        }
    } 


}

Please help me how to write.

like image 962
user8363477 Avatar asked Jan 17 '26 05:01

user8363477


1 Answers

You can use Mockito to:

  • Create an instance of postData with mocked RestTemplate and Environment
  • Set expectations on these which allow the ``postJSONData` call to complete
  • Verify that the mocked RestTemplate is invoked correctly

The postJSONData method does not use the restTemplate.postForObject() response so the best you can do in terms of testing this method is to verify that restTemplate.postForObject() is invoked with the correct parameters.

Here's an example:

@RunWith(MockitoJUnitRunner.class)
public class PostDataTest {

    @Mock
    private RestTemplate restTemplate;
    @Mock
    private Environment env;

    @InjectMocks
    private PostData postData;

    @Test
    public void test_postJSONData() {
        String baseUrl = "theBaseUrl";
        String resourcePath = "aResourcePath";

        Mockito.when(env.getProperty("baseURL")).thenReturn(baseUrl);
        Mockito.when(env.getProperty("resourcePath")).thenReturn(resourcePath);

        List<String> payload = new ArrayList<>();

        postData.postJSONData(payload);

        // it's unclear from your posted code what goes into the HttpEntity so
        // this approach is lenient about its expectation
        Mockito.verify(restTemplate).postForObject(
                Mockito.eq(baseUrl + resourcePath),
                Mockito.any(HttpEntity.class),
                Mockito.eq(String.class)
        );

        // assuming that the HttpEntity is constructed from the payload passed 
        // into postJSONData then this approach is more specific
        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/json");
        Mockito.verify(restTemplate).postForObject(
                Mockito.eq(baseUrl + resourcePath),
                Mockito.eq(new HttpEntity<>(payload.toString(), headers)),
                Mockito.eq(String.class)
        );
    }
}

On a side note; postData is an unusual name for a class and the postJSONData method provided in your OP doesn't compile; it references meterReadings rather than data.

like image 86
glytching Avatar answered Jan 19 '26 19:01

glytching



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!