1

following is my method which I am trying to unit test
public class Emp {
  public String getName() {
    ResponseEntity<LinkedHashMap> res = restTemplate.postForEntity(url, null, LinkedHashMap.class);
    return res.getBody().get("name");
  }
}

My unit test code is as follows

        LinkedHashMap<String, String> map = new LinkedHashMap<>();
        map.put("name", "foo");
        ResponseEntity<LinkedHashMap> entity = new ResponseEntity<>(map, HttpStatus.OK);

        Mockito.when(restTemplate.postForEntity(Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(entity);

But I am getting compilation error as

java: no suitable method found for thenReturn(org.springframework.http.ResponseEntity<java.util.LinkedHashMap>)

Couldn't get rid of the error after many trial n error.
Can someone point at whats wrong here and how I can fix the unit test code?

thanks

1 Answer 1

0

Couldn't get rid of the error after many trial n error. Can someone point at whats wrong here and how I can fix the unit test code?

You have this compilation error because you try to use thenReturn with a generic type ResponseEntity<LinkedHashMap>. Mockito expects you to use thenReturn with a specific instance, but not just a generic type.

You can fix this error by using the ResponseEntity class with the specific generic type which matches your method's return value type:

.
..
...

LinkedHashMap<String, String> map = new LinkedHashMap<>();
map.put("name", "foo");
ResponseEntity<LinkedHashMap<String, String>> entity = new ResponseEntity<>(map, HttpStatus.OK);

Mockito.when(restTemplate.postForEntity(Mockito.anyString(), Mockito.isNull(), Mockito.eq(LinkedHashMap.class)))
               .thenReturn(entity);

...
..
.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.