I am working on a REST api using Spring-MVC and json. I running my automatic tests using Jetty and an in-memory database. I want to test that posting an invalid domain object gives me the error message from the @NotEmpty annotation. But all I get is the default Jetty 400 Bad Request page.
I have a domain class with some validation:
@Entity
public class Company {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotEmpty(message = "Name is a required field")
private String name;
/* getters, setters */
}
Here’s the controller
@Controller
public class CompanyController {
@RequestMapping(value = "/company",
method = RequestMethod.POST,
consumes = "application/json")
public void createCompany(
@Valid @RequestBody final Company company,
final HttpServletResponse response) {
//persist company
response.setStatus(HttpServletResponse.SC_CREATED);
response.setHeader("location", "/company/" + company.getId());
}
}
How can I get the value "Name is a required field" returned as part of the response?
This does it: