Issue
Is it possible to do integration test for null check. I passed null value.
HttpEntity<Employee> entity = new HttpEntity<Employee>(null, headers);
restTemplate.exchange(url, httpMethod, entity, String.class);
{"timestamp":"2018-10-06T14:33:52.113+0000","status":400,"error":"Bad Request","message":"Required request body is missing:"}
@RestController
public class EmployeeController {
@PostMapping(value = "/employee/save", produces = "application/json")
public Employee save(@RequestBody Employee employee){
if(employee==null){
throw new RuntimeException("Employee is null");
}
}
}
class Employee {
}
Solution
@RequestBody(required=false) Employee employee
please try with required option in @RequestBody.
The problem here is the mapping in spring mvc.
required
Default is true, leading to an exception thrown in case there is no body content. Switch this to false if you prefer null to be passed when the body content is null.
@RequestBody Employee employee
Your method only is processed the request if employee is not null. Then it considered mapping correctly and pass request to this method and handle it. So the check null condition will be needless here.
Answered By - Huy Nguyen
Answer Checked By - Marilyn (JavaFixing Volunteer)