How to mock the ResponseEntity<?> with generic type?

24,400

First, create a ResponseEntity object:

HttpHeaders header = new HttpHeaders();
header.setContentType(MediaType.APPLICATION_JSON);

ResponseEntity<?> responseEntity = new ResponseEntity<>(
    "some response body",
    header, 
    HttpStatus.OK
);

Then build a mock to return the responseEntity object:

when(restC.SomeMethod(client)).thenReturn(responseEntity);

Point to pay attention:

Avoid to use ResponseEntity inside @Service class. You should use ResponseEntity in @RestController class.

And you can Inject your @Service class using @Autowired annotation, like:

@RestController
public class YourControllerClass {

    @Autowired
    private YourServiceClass yourServiceClass;

Or using constructor, like:

@RestController
public class YourControllerClass {

    private YourServiceClass yourServiceClass;

    public YourControllerClass(YourServiceClass yourServiceClass) {
        this.yourServiceClass= yourServiceClass;
    }

So:

@Service class will handle business or data objects and @RestController class will handle Response and Request objects. Thus we have Single Responsibility principle.


Some nice links:

Hope this helps!

Share:
24,400
Still Alive
Author by

Still Alive

Updated on July 09, 2022

Comments

  • Still Alive
    Still Alive almost 2 years

    I need to mock a service. i m getting null in ResponseEntity<?> resp while mocking the class.

    Method which need to mock:

    public List<Expression> getExpression(String expressView, Localdate date) {
    
        List<Expression> =new ArrayList<>();
        Map<String, Object> uri = new HashMap<>();
        UriComponenetsBuilder build = 
            UriComponentsBuilder.fromHttpUrl("someUrl" + "/" + expressView);
        build.queryParam(someParameter, someParameter);
        build.queryParam(someParameter, someParameter);
        build.queryParam(someParameter, someParameter);
    
        HttpHeaders header = new HttpHeaders();
        header.setContentType(MediaType.APPLICATION_JSON);
        RestClient client = new RestClient(
            build.build().encode.toUriString, HttpMethod.GET.Uri, header
        );
    
        ResponseEntity<?> resp = restC.SomeMethod(client);
    
        if (resp = !null) {
            //it goes to these line
        }
    
      }
    

    In my mock method:

    when(restC.SomeMethod(client)).thenReturn(resp);
    

    So above method call a service get some data get the value of expressView and save as list. when i mocked the method when(restC.SomeMethod(client)).thenReturn(resp); it hit the URL but the value i m getting as response resp is null . So here i m getting the resp value as null. I checked the URL(someUrl) in postman its returning the value.

    How to mock the ResponseEntity<?>?

    Thanks.

  • Juliano Macedo
    Juliano Macedo over 5 years
    I improved my answer with suggestions, examples and some nice links ;) I hope this will help you.