我想为返回json的spring restful web服务实现测试用例 我的控制器测试类是:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {WebAppContext.class,JpaTestConfiguration.class
})
@WebAppConfiguration
public class DominProfileRestControllerTest {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext webApplicationContext;
private MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(),
MediaType.APPLICATION_JSON.getSubtype(),
Charset.forName("utf8"));
@Before
public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@Test
public void testGetDomainProfile() throws Exception {
String profileId = domainProfile.getId().toString();
System.out.print("testing restful"+profileId);
mockMvc.perform(get("/service/domainprofile/get/{id}", profileId) )
.andExpect(status().isOk())
.andExpect(content().contentType(contentType))
.andExpect(jsonPath("$.city", is("Chandigrah")));
/* mockMvc.perform(get("/service/domainprofile/get/{id}",profileId).accept(MediaType.TEXT_PLAIN))
.andExpect(status().isOk())
.andExpect(content().contentType("text/plain;charset=ISO-8859-1"))
.andExpect(content().string("hello Prashant"));
*/
}
我的控制器类是:
@RestController
@RequestMapping("/service/domainprofile")
public class DominProfileRestController {
@Autowired
private JpaDomainProfileRepository jpaDomainProfileRepository;
@RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
public DomainProfileResource getDomainProfile(@PathVariable String id) {
JpaDomainProfile domainProfile = jpaDomainProfileRepository.findOne(Long.valueOf(id));
DomainProfileResource domainProfileResource = new DomainProfileResource();
System.out.println("domainProfile.getCity()*************" + domainProfile.getCity());
System.out.println("domainProfile.getAddress()*************" + domainProfile.getAddress());
domainProfileResource.setCity(domainProfile.getCity());
domainProfileResource.setAddress(domainProfile.getAddress());
// return new ResponseEntity<DomainProfileResource>(domainProfileResource, HttpStatus.OK);
return domainProfileResource;
// return domainProfile;
}
}
当我运行测试用例时,我在domainprofile.city和domainprofile.address中获取了值时出现了错误。 错误是: java.lang.AssertionError:状态 预计:200 实际:500 当我返回纯文本时它工作正常
答案 0 :(得分:5)
mockMvc.perform(get(“/ service / domainprofile / get / {id}”,profileId)) .andDo(印刷());
这将打印带有异常的完整响应,现在如果您看到HttpMessageNotWritableException这是我面临的问题,您应该尝试使用jackson序列化您的对象并查看它是否有效(spring内部使用Jackson)。例如,如果您的任何字段为空,则序列化将失败。