Author | Message |
---|---|
Victor
Posts: 23
|
Posted 20:05 Oct 15, 2018 |
Hi Professor. I just used mockmvc to send a user object without an email (Expecting it to fail) to my registration endpoint. For some reason, it works. A 200 status code is returned and the response body contains a user object with the email being null. If I send the same user object to the server without the email (using postman), it returns an error as expected because of my 'nullable = false' constraint on the email property. What am I doing wrong? |
cysun
Posts: 2935
|
Posted 21:15 Oct 15, 2018 |
The not-null constraint is enforced at the database level so it shouldn't matter how the request is sent in. In the case of Mockmvc, is the user object saved in database? Does the response json contain a generated id? |
Victor
Posts: 23
|
Posted 13:39 Oct 16, 2018 |
When I check the database, nothing is saved. An ID is generated for the User object in the response body. Below is the response body: MockHttpServletRequest: Handler: Async: Resolved Exception: ModelAndView: FlashMap: MockHttpServletResponse:
Below is my UserControllerTest code: @Test User user = new User(); mockMvc.perform( post("/user") System.out.println(user.toString()); |
cysun
Posts: 2935
|
Posted 14:25 Oct 16, 2018 |
(a) You should check missing field in your controller code and send appropriate status code and error message. Relying on database constraint check for this purpose is not good because you'll then get a SQL exception, and unless you examine the exception, you cannot tell whether it's caused by some missing fields (i.e. client error and should send back 4xx status codes ) or some server problem (e.g. incorrect SQL syntax and should send back 5xx status codes). (b) The super class I used for the test examples (and I assume you are using the same) is You can change this default behavior by using an annotation @Rollback(false) on the test method. I've added a couple of addUser test cases in my springrest example and one of them has the @Rollback annotation. |