Hi Johan,
I am creating JUNIT tests for my Spring MVC REST API controllers as per
http://www.jayway.com/2014/01/14/unit-testing-spring-mvc-controllers-with-rest-assured/ Everything is working well for us except for testing field validations for controllers that use the @Valid annotation.
This may likely be related to the more general Spring MVC testing issue found at this stackoverflow posting. We are experience the same end behaviour.
http://stackoverflow.com/questions/12308213/how-do-i-get-spring-mvc-to-invoke-validation-in-a-junit-testHere's snippets of the code in question:
a) Controller Snippet:
public RestResponseObject handleCreate(HttpServletRequest request, @PathVariable(value = "loginId") String loginId,
@Valid @RequestBody CreateUser createUser) {
b) POJO/Data Bean Snippet:
public class CreateUser {
…
@Size(min = 8, max = 20)
private String userPassword;
…
c) Test Snippet
We first create a createUser with invalid field(s) - in this case, a password that is too short.
import static com.jayway.restassured.module.mockmvc.RestAssuredMockMvc.*;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItems;
....
@Test
@Override
public void testCreateFieldValidation() {
...
given().
standaloneSetup(new UserController()).contentType(ContentType.JSON).
body(createUser).
when().
post("/user/" + loginId).
then().
statusCode(HttpStatus.BAD_REQUEST.value()).etc ….
...
What happens is that the controller never gets invoked (nor does the interceptor that handles the expected MethodArgumentNotValidException).
The result is the following:
java.lang.IllegalStateException: Expected response body to be verified as JSON, HTML or XML but content-type 'null' is not supported out of the box.
Try registering a custom parser using:
RestAssured.registerParser("null", <parser type>);