Unit testing

The code to unit test the created Todo is shown as follows:

    @Test
public void createTodo() throws Exception {
Todo mockTodo = new Todo(CREATED_TODO_ID, "Jack",
"Learn Spring MVC", new Date(), false);
String todo = "{"user":"Jack","desc":"Learn Spring MVC",
"done":false}";

when(service.addTodo(anyString(), anyString(),
isNull(),anyBoolean()))
.thenReturn(mockTodo);

mvc
.perform(MockMvcRequestBuilders.post("/users/Jack/todos")
.content(todo)
.contentType(MediaType.APPLICATION_JSON)
)
.andExpect(status().isCreated())
.andExpect(
header().string("location",containsString("/users/Jack/todos/"
+ CREATED_TODO_ID)));
}

A few important things to note are as follows:

  • String todo = "{"user":"Jack","desc":"Learn Spring MVC","done":false}": The Todo content to post to the create todo service.
  • when(service.addTodo(anyString(), anyString(), isNull(), anyBoolean())).thenReturn(mockTodo): Mocks the service to return a dummy todo.
  • MockMvcRequestBuilders.post("/users/Jack/todos").content(todo).contentType(MediaType.APPLICATION_JSON)): Creates a POST to a given URI with the given content type.
  • andExpect(status().isCreated()): Expects that the status is created.
  • andExpect(header().string("location",containsString("/users/Jack/todos/" + CREATED_TODO_ID))): Expects that the header contains location with the URI of created resource.
..................Content has been hidden....................

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