Unit testing

The code to unit test the TodoController class is shown in the following screenshot:

   @RunWith(SpringRunner.class)
@WebMvcTest(TodoController.class)
public class TodoControllerTest {

@Autowired
private MockMvc mvc;

@MockBean
private TodoService service;

@Test
public void retrieveTodos() throws Exception {
List<Todo> mockList = Arrays.asList(new Todo(1, "Jack",
"Learn Spring MVC", new Date(), false), new Todo(2, "Jack",
"Learn Struts", new Date(), false));

when(service.retrieveTodos(anyString())).thenReturn(mockList);

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

String expected = "["
+ "{id:1,user:Jack,desc:"Learn Spring MVC",done:false}" +","
+ "{id:2,user:Jack,desc:"Learn Struts",done:false}" + "]";

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

A few important things to note are as follows:

  • We are writing a unit test. So, we want to test only the logic present in the TodoController class. So, we initialize a Mock MVC framework with only the TodoController class using @WebMvcTest(TodoController.class).
  • @MockBean private TodoService service: We are mocking out the TodoService using the @MockBean annotation. In test classes that are run with SpringRunner, the beans defined with @MockBean will be replaced by a mock, created using the Mockito framework.
  • when(service.retrieveTodos(anyString())).thenReturn(mockList): We are mocking the retrieveTodos service method to return the mock list.
  • 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): JSONAssert is a very useful framework to perform asserts on JSON. It compares the response text with the expected value. JSONAssert is intelligent enough to ignore values that are not specified. Another advantage is a clear failure message in case of assertion failures. The last parameter, false, indicates using non-strict mode. If it is changed to true, then the expected should exactly match the result.
..................Content has been hidden....................

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