弹簧测试406错误

时间:2014-03-20 20:32:25

标签: json spring-mvc junit spring-test-mvc

我需要使用spring test framework在我的控制器中测试一个方法:

@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

已解决的异常:                 Type = 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(){
        }
    });
});

0 个答案:

没有答案