Skip to content
Advertisement

What is the purpose of mockMvc .contentType(MediaType.APPLICATION_JSON)?

I don’t understand the point of this method and can’t find any info about it. What is the reason of using it, especially for void methods like in example below? I’ve tried deleting it in my tests and seems like everything is the same. Test

   @Test
public void deletePatientById_success() throws Exception {
    Mockito.when(patientRecordRepository.findById(RECORD_2.getPatientId())).thenReturn(Optional.of(RECORD_2));

    mockMvc.perform(MockMvcRequestBuilders
            .delete("/patient/2")
            .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk());
}

Controller to be tested

    @DeleteMapping(value = "{patientId}")
public void deletePatientById(@PathVariable(value = "patientId") Long patientId) throws NotFoundException {
    if (patientRecordRepository.findById(patientId).isEmpty()) {
        throw new NotFoundException("Patient with ID " + patientId + " does not exist.");
    }
    patientRecordRepository.deleteById(patientId);
}

Advertisement

Answer

The contentType method does not belong to the mockMvc class but to the MockHttpServletRequestBuilder class and it sets the ‘Content-Type’ header of the request to a specific type (in this case you inform the endpoint that the request body format of your request is JSON).

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement