我想为spring restful web服务实现测试用例,它返回一个json MY控制器测试类是:
@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"));
*/
}
Run Code Online (Sandbox Code Playgroud)
我的Controller类是:
@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;
}
}
Run Code Online (Sandbox Code Playgroud)
当我运行测试用例时,我在domainprofile.city和domainprofile.address中获取了值时出现了错误.错误是:java.lang.AssertionError:状态预期:200实际:500它正常工作当我返回纯文本时
小智 5
你能做这个吗
mockMvc.perform(get("/ service/domainprofile/get/{id}",profileId)).and Do(print());
这将打印带有异常的完整响应,现在如果您看到HttpMessageNotWritableException这是我面临的问题,您应该尝试使用jackson序列化您的对象并查看它是否有效(spring内部使用Jackson).例如,如果您的任何字段为空,则序列化将失败.
归档时间: |
|
查看次数: |
2526 次 |
最近记录: |