Unit testing

The code to unit test retrieveTodo is as follows:

     @Test
public void retrieveTodo() throws Exception {
Todo mockTodo = new Todo(1, "Jack", "Learn Spring MVC",
new Date(), false);

when(service.retrieveTodo(anyInt())).thenReturn(mockTodo);

MvcResult result = mvc.perform(
MockMvcRequestBuilders.get("/users/Jack/todos/1")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk()).andReturn();

String expected = "{id:1,user:Jack,desc:"Learn Spring
MVC",done:false}";

JSONAssert.assertEquals(expected,
result.getResponse().getContentAsString(), false);

}

A few important things to note are as follows:

  • when(service.retrieveTodo(anyInt())).thenReturn(mockTodo): We are mocking the retrieveTodo service method to return the mock todo.
  • MvcResult result = ..: We are accepting the result of the request into an MvcResult variable to enable us to perform assertions on the response.
  • JSONAssert.assertEquals(expected, result.getResponse().getContentAsString(), false): Asserts whether the result is as expected.
..................Content has been hidden....................

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