I have a Spring Boot Controller with POST. Method works fine. I tested it by POSTMAN and from postgresql I recieved JSON. But I need test it.
@RestController @RequestMapping("/api") public class FamilyController { private final FamilyService familyService; public FamilyController(FamilyService familyService) { this.familyService = familyService; } @GetMapping("/getFamily/{familyId}") public List<FamilyMember> getFamily(@PathVariable Integer familyId) { return familyService.searchFamilyMember(familyId); } }
I created test:
@ExtendWith(SpringExtension.class) @WebMvcTest(FamilyController.class) class FamilyControllerTest { @Autowired private MockMvc mockMvc; @Autowired private ObjectMapper objectMapper; @MockBean private FamilyService service; @Captor private ArgumentCaptor<Family> argumentCaptor; @Test void createFamily() throws Exception { Family family = new Family(); family.setId(1); family.setFamilyName("Kowal"); family.setNrOfInfants(2); family.setNrOfChildren(2); family.setNrOfAdults(1); Mockito.when(service.saveAndFlush(argumentCaptor.capture())).thenReturn(1); mockMvc.perform(post("/api/createFamily") .contentType(MediaType.APPLICATION_JSON) .contentType(objectMapper.writeValueAsString(family))) .andExpect(status().isCreated()); // .andExpect(header().exists("Location")) // .andExpect(header().string("Location", "http://localhost/api/getFamily/1")); assertThat(argumentCaptor.getValue().getFamilyName(), is("Kowal")); }
when I run a test, I received error like below:
WARN 15404 --- [ main] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Invalid mime type "{"id":1,"familyName":"Kowal","nrOfInfants":2,"nrOfChildren":2,"nrOfAdults":1,"familyMembers":[]};charset=UTF-8": does not contain '/']
What am I doing wrong?
Advertisement
Answer
The problem is this line:
.contentType(objectMapper.writeValueAsString(family)))
Right now you are sending the object in the content-type header, that’s why you get the error message.
Change it to:
.content(objectMapper.writeValueAsString(family)))