Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to check the type returned by ResponseEntity<?>

I have a Spring REST Api that adds users to a db:

@PostMapping(value = "/adduser", produces = "application/json")
public ResponseEntity<?> addUser(@RequestBody User user){...}

Now I’m creating it’s unit test where I placed this code:

ResponseEntity<?> user = userController.addUser(userTest);

The addUser method will either return a ResponseEntity<User> containing the json of the added user (when it’s added successfully) or return a ResponseEntity<String> with an error message when an error occurred.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Now, how can I check which of those two was actually returned?

I want to use that information to create two Assert tests. One where userTest will be valid (expecting the User object as return) and one where userTest will be invalid input (expecting the String error message as return).

>Solution :

you can just use instanceof operator, as follow :

if(user.getBody() instanceof String) {
   // -- do something
}
if(user.getBody() instanceof User) {
  // -- do this
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading