Unit testing validations

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 failure for the @Size(min = 9, message = "Enter atleast 10 Characters.") check.
  • .andExpect(status().is4xxClientError()): Checks for validation error status.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset