我需要使用 spring 测试框架在我的控制器中测试一个方法:
@RequestMapping(value="/retrieve", method = RequestMethod.GET)
@ResponseBody
public Map<String, String> goRetrieve(){
return retrieveService.retrieveData();
}
测试方法:
@Before
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
Map<String, String> testMap = new HashMap<String, String>();
testMap.put("test", "[{\"name\": \"john\" }]");
RetrieveService retrieveService = org.mockito.Mockito
.mock(RetrieveService.class);
when(retrieveService.retrieveData()).thenReturn(testMap);
}
@Test
public void testGetretrieve() throws Exception {
mockMvc.perform(get("/retrieve")
.accept(MediaType.ALL))
.andExpect(status().isOk());
}
但是,JUnit 测试不断抱怨有一个错误的请求
Status expected:<200> but was:<406>
但是,当我更改方法以使其返回 String
@RequestMapping(value="/retrieve", method = RequestMethod.GET)
@ResponseBody
public String goRetrieve(){
return retrieveService.retrieveData().toString();
}
测试类以这种方式运行良好。
我觉得这太奇怪了。因为我的应用程序在启动时运行良好,这意味着 Jackson 可以工作并且可以将 Map 映射到 JSON 对象,但为什么它在 JUnit 测试中失败?
非常感谢!
EIDT:
MockHttpServletRequest:
HTTP Method = GET
Request URI = /retrieve
Parameters = {}
Headers = {Accept=[application/json]}
Handler:
Type = com.luo.calculator.controller.RetrieveController
Async:
Was async started = false
Async result = null
已解决的异常:类型 = org.springframework.web.HttpMediaTypeNotAcceptableException
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
MockHttpServletResponse:
Status = 406
Error message = null
Headers = {}
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
我在 JSP 中的 ajax 请求:
$("#history").click(function() {
$.ajax({
type: 'GET',
url: '<c:url value = "/retrieve" />',
dataType: 'json',
success: function(data) {
error:function(){
}
});
});