我试图测试我的休息控制器。没有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)
并且不是空的。
编辑:
添加控制器代码:
@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);
}
答案 0 :(得分:2)
解决。
模拟调用应使用any
而不是具体对象:when(serviceMock.addCompany(any(Company.class))).thenReturn(e);
我需要覆盖实体类的equals方法来传递此语句:verify(serviceMock, times(1)).addCompany(e);