我正在尝试测试我的休息控制器。 GET没问题,但是当我尝试测试POST方法时,无法附加主体。

private static final MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(),
                                                            MediaType.APPLICATION_JSON.getSubtype(),
                                                            Charset.forName("utf8"));
private ObjectMapper jsonMapper = new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL);

@Test
public void test1() throws Exception {
    //...Create DTO
    //...Create same pojo but as entity

    when(serviceMock.addEntity(e)).thenReturn(e);

    mvc.perform(post("/uri")
        .contentType(contentType)
        .content(jsonMapper.writeValueAsString(dto))
        )
        .andDo(print())
        .andExpect(status().isCreated())
        .andExpect(content().contentType(contentType)); //fails because there is no content returned
}

这是请求输出:
MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /uri
       Parameters = {}
          Headers = {Content-Type=[application/json;charset=UTF-8]}

没有身体。为什么?我已经打印了jsonMapper.writeValueAsString(dto),但不为null。

编辑:

添加控制器代码:
@RestController
@RequestMapping("/companies")
public class CompanyController {

    @Autowired
    private CompanyService service;
    @Autowired
    private CompanyMapper mapper;



    @RequestMapping(method=RequestMethod.GET)
    public List<CompanyDTO> getCompanies() {
        List<Company> result = service.getCompanies();
        return mapper.toDtoL(result);
    }

    @RequestMapping(method=RequestMethod.POST)
    @ResponseStatus(HttpStatus.CREATED)
    public CompanyDTO createCompany(@RequestBody @Valid CompanyDTO input) {
        Company inputE = mapper.toEntity(input);
        Company result = service.addCompany(inputE);
        return mapper.toDto(result);
    }

最佳答案

解决了。

  • 模拟调用应使用any而不是具体对象:when(serviceMock.addCompany(any(Company.class))).thenReturn(e);
  • 我需要重写实体类的equals方法以传递此语句:verify(serviceMock, times(1)).addCompany(e);
  • 10-06 16:10