Let's start with writing a unit test to retrieve all todos—http://localhost:8080/users/Jack/todos. The following code is an example response:
[
{
"id":1,
"user":"Jack",
"desc":"Learn Spring MVC",
"targetDate":"2019-01-08T12:42:42.337+0000",
"done":false
},
{
"id":2,
"user":"Jack",
"desc":"Learn Struts",
"targetDate":"2019-01-08T12:42:42.337+0000",
"done":false
}
]
The REST API uses the service.retrieveTodos method to retrieve the Todo details for a user. In a unit test, we want to mock the service, and configure a mock response. We can do this using Mockito:
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);
When the retrieveTodos method is called, it will return a mock hardcoded response.
Here's the complete unit test:
@Test
public void retrieveTodos() throws Exception {
//GIVEN
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);
//WHEN
MvcResult result = mvc.perform(
MockMvcRequestBuilders.get("/users/Jack/todos")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk()).andReturn();
//THEN
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);
}
JSONAssert is a very useful framework that is used to perform asserts on JSON. It compares the response text with the expected value:
JSONAssert.assertEquals(expected, result.getResponse().getContentAsString(), false)
The last parameter, false, indicates the use of a non-strict mode. In a non-strict mode, JSONAssert only compares the elements that are specified in the expected JSON string. If it is changed to true, then the expected string should exactly match the result.