The following example shows how we can unit test the validations we added in:
@Test public void createTodo_withValidationError() throws Exception { Todo mockTodo = new Todo(CREATED_TODO_ID, "Jack", "Learn Spring MVC", new Date(), false); String todo = "{"user":"Jack","desc":"Learn","done":false}"; when( service.addTodo( anyString(), anyString(), isNull(), anyBoolean())) .thenReturn(mockTodo); MvcResult result = mvc.perform( MockMvcRequestBuilders.post("/users/Jack/todos") .content(todo) .contentType(MediaType.APPLICATION_JSON)) .andExpect( status().is4xxClientError()).andReturn(); }
Some important points to note are as follows:
- "desc":"Learn": We are using a desc value of length 5. This would cause a validation ...