2

I need to test a method in my controller using spring test framework:

@RequestMapping(value="/retrieve", method = RequestMethod.GET)
@ResponseBody
public Map<String, String> goRetrieve(){
    return retrieveService.retrieveData();
}

The test methods:

@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());

}

However, JUnit test keeps complaining there is a bad request

Status expected:<200> but was:<406> 

However, when I changed the method to make it return a String

@RequestMapping(value="/retrieve", method = RequestMethod.GET)
@ResponseBody
public String goRetrieve(){
    return retrieveService.retrieveData().toString();
}

the test class works good in this way.

I think this is so weird. Because my application runs well when it starts, which means the Jackson works and it can map a Map to JSON object, but why it fails in the JUnit tests?

Thank you very much!

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

Resolved Exception: 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 = []

My ajax request in JSP:

$("#history").click(function() {
    $.ajax({
        type: 'GET',
        url: '<c:url value = "/retrieve" />',
        dataType: 'json',
        success: function(data) {
        error:function(){
        }
    });
});
roland luo
  • 1,561
  • 4
  • 19
  • 24

0 Answers0