如何在 Spring 控制器中的 Spring REST 中创建单元测试

How create unit test in Spring REST in POST Cotroller

我有一个 Spring 引导控制器 POST。方法工作正常。我通过 POSTMAN 测试了它,我从 postgresql 收到了 JSON。但我需要测试一下。

@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);
    }
}

我创建了测试:

@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"));
    }

当我 运行 测试时,我收到如下错误:

 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 '/']

我做错了什么?

问题出在这一行:

.contentType(objectMapper.writeValueAsString(family)))

现在您正在 content-type header 中发送 object,这就是您收到错误消息的原因。

改为:

.content(objectMapper.writeValueAsString(family)))