iCo*_*ode 53 java json spring-mvc junit4
嗨,我有一个Spring mvc控制器
@RequestMapping(value = "/jobsdetails/{userId}", method = RequestMethod.GET)
@ResponseBody
public List<Jobs> jobsDetails(@PathVariable Integer userId,HttpServletResponse response) throws IOException {
try {
Map<String, Object> queryParams=new LinkedHashMap<String, Object>();
queryParams.put("userId", userId);
jobs=jobsService.findByNamedQuery("findJobsByUserId", queryParams);
} catch(Exception e) {
logger.debug(e.getMessage());
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
}
return jobs;
}
Run Code Online (Sandbox Code Playgroud)
我想看看运行它时JSON字符串的样子.我写了这个测试用例
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration("classpath:webapptest")
@ContextConfiguration(locations = {"classpath:test-applicationcontext.xml"})
public class FindJobsControllerTest {
private MockMvc springMvc;
@Autowired
WebApplicationContext wContext;
@Before
public void init() throws Exception {
springMvc = MockMvcBuilders.webAppContextSetup(wContext).build();
}
@Test
public void documentsPollingTest() throws Exception {
ResultActions resultActions = springMvc.perform(MockMvcRequestBuilders.get("/jobsdetails/2").accept(MediaType.APPLICATION_JSON));
System.out.println(/* Print the JSON String */); //How ?
}
}
Run Code Online (Sandbox Code Playgroud)
如何获取JSON字符串?
我正在使用Spring 3,Codehause Jackson 1.8.4
JB *_*zet 126
试试这段代码:
resultActions.andDo(MockMvcResultHandlers.print());
Run Code Online (Sandbox Code Playgroud)
jax*_*jax 68
诀窍是使用 andReturn()
MvcResult result = springMvc.perform(MockMvcRequestBuilders
.get("/jobsdetails/2").accept(MediaType.APPLICATION_JSON)).andReturn();
String content = result.getResponse().getContentAsString();
Run Code Online (Sandbox Code Playgroud)
对我来说,当我使用下面的代码时,它有效:
ResultActions result =
this.mockMvc.perform(post(resource).sessionAttr(Constants.SESSION_USER, user).param("parameter", "parameterValue"))
.andExpect(status().isOk());
String content = result.andReturn().getResponse().getContentAsString();
Run Code Online (Sandbox Code Playgroud)
它工作了!! :d
希望我可以用我的答案帮助对方
您可以在设置MockMvc实例时启用每种测试方法的打印响应.
springMvc = MockMvcBuilders.webAppContextSetup(wContext)
.alwaysDo(MockMvcResultHandlers.print())
.build();
Run Code Online (Sandbox Code Playgroud)
请注意.alwaysDo(MockMvcResultHandlers.print())上面代码的一部分.这样就可以避免为每个测试方法应用print处理程序.
| 归档时间: |
|
| 查看次数: |
50736 次 |
| 最近记录: |