This post shows how to unit test RESTful API URLs using Spring Boot 1.5.10RELEASE. Sometimes, we want to ensure the list of URLs still work and match to what have been documented per specification.
Authenticate User – Controller
We have a simple controller that supposedly authenticates users. Notice we do not have the actual codes to perform the authentication. That’s fine!
When we test for only the URL, the implementation of a method does not matter.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | ... @RestController @RequestMapping("/api/public/authenticate") public class UserAuthenticationController { private final Logger LOGGER = Logger.getLogger(this.getClass()); @RequestMapping(method = RequestMethod.POST) public ResponseEntity<AuthenticationResponseDTO> authenticationRequest( @RequestBody AuthenticationRequestDTO authenticationRequest) { // Delegate processing to some service to authenticate user // This log will not be available in the console log LOGGER.info(authenticationRequest.getUsername() + "|" + authenticationRequest.getPassword()); AuthenticationResponseDTO dto = new AuthenticationResponseDTO(); dto.setToken(UUID.randomUUID().toString()); return ResponseEntity.ok(dto); } } |
Unit Test
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | ... @RunWith(SpringRunner.class) @WebMvcTest(value = UserAuthenticationController.class) public class UserAuthenticationControllerTest { private final Logger LOGGER = Logger.getLogger(this.getClass()); @Autowired private MockMvc mockMvc; @MockBean private UserAuthenticationController userAuthenticationController; @Test public void testSearchForTravelInsuranceProducts() throws Exception { ObjectMapper objectMapper = new ObjectMapper(); AuthenticationRequestDTO authenticationRequestDTO = new AuthenticationRequestDTO(); authenticationRequestDTO.setUsername("awesome"); authenticationRequestDTO.setPassword("awesome!password"); String jsonInString = objectMapper.writeValueAsString(authenticationRequestDTO); LOGGER.info("Start - Test"); mockMvc.perform(post("/api/public/authenticate") .contentType(MediaType.APPLICATION_JSON).content(jsonInString)) .andExpect(status().isOk()); LOGGER.info("End - Test"); } } |
Sample Output
Notice there is no text written from our controller.
Download the Codes
https://github.com/Turreta/Spring-Boot-How-to-unit-test-RESTful-API-URLs