How to mock the ResponseEntity<?> with generic type?
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 useResponseEntity
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 handlebusiness or data objects
and@RestController class
will handleResponse
andRequest
objects. Thus we haveSingle Responsibility
principle.
Some nice links:
- Spring MVC - Using RequestEntity and ResponseEntity
- How do I mock a REST template
- Building REST services with Spring
- Understanding the Single Responsibility Principle
Hope this helps!
Still Alive
Updated on July 09, 2022Comments
-
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 responseresp
is null . So here i m getting theresp
value asnull
. I checked the URL(someUrl) in postman its returning the value.How to mock the
ResponseEntity<?>
?Thanks.
-
Juliano Macedo over 5 yearsI improved my answer with suggestions, examples and some nice links ;) I hope this will help you.