As we have written few methods in our controller, let's write quick unit tests for couple of methods:
@RunWith(SpringRunner.class) @WebMvcTest(TodoController.class) public class TodoControllerTest { @Autowired private MockMvc mvc; @MockBean private TodoServiceImpl todoService; private final String BASE_PATH_V1 = "/api/1/0"; @Test public void testHello() throws Exception { mvc.perform( get(BASE_PATH_V1 + "/hello")) .andExpect(status().isOk()) .andExpect(content().string("Hello Rest demo")); } @Test public void testGetUsers() throws Exception { //Mock setup Map<Integer, String> expected = new HashMap<>(); expected.put(1, "Todo - 1"); expected.put(2, "Todo - 2"); Mockito.when(todoService.getTodos()).thenReturn(expected); //perform call MvcResult result = mvc.perform( get(BASE_PATH_V1+ "/todos")) .andExpect(status().isOk()).andReturn(); ObjectMapper mapper = new ObjectMapper(); Map actual = mapper.readValue(result.getResponse().getContentAsString(), Map.class); //Assertions Mockito.verify(todoService, Mockito.times(1)).getTodos(); Assertions.assertEquals(expected.size(), actual.size()); Assertions.assertEquals(expected.get(1), actual.get("1")); } }
In the above controller test, we are testing two endpoints "/hello" and "/todos"
important annotations:
@RunWith(SpringRunner.class)
- This is used to let spring know that it needs to a launch Spring context for unit testing
@WebMvcTest(TodoController.class)
- This will make sure that beans annotated with Spring-MVC-related annotations are loaded
MockMvc
- MockMvc is used to make the requests
test code
Happy Coding 👨💻
Comments
Post a Comment