0

i am trying to do integration tests for my controllers, but for some reason the test context fails to parse back the response and causes the test to fail, and throwing 406 HTTP code.

I have jackson mapper bean in context.

Here is the code:

Controller:

@Controller
@RequestMapping({"/user"})
public class UserController 
{
    Logger logger = LoggerFactory.getLogger(UserController.class);
    @RequestMapping(value = "isloggedin",method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public ServerResponse<Boolean> isloggedin() {
    return new ServerResponse<Boolean>(true, HttpStatus.OK, "logged in");
}

Test context:

@PropertySources(value = { @PropertySource("classpath:/application.properties")})
@ComponentScan(basePackages = {"X.Y.Z.controllers", "X.Y.Z.webresources"})
@ContextConfiguration(classes = {WebMvcConfig.class})
public class ControllerIntegrationUnitTestContext extends AbstractJUnit4SpringContextTests {}

inside WebMvcConfig i have:

@Bean
@Autowired
public RequestMappingHandlerAdapter requestMappingHandlerAdapter(MappingJackson2HttpMessageConverter d){
    RequestMappingHandlerAdapter requestMappingHandlerAdapter = new RequestMappingHandlerAdapter();
    List<HttpMessageConverter<?>> messageConverters = new LinkedList<>();
    messageConverters.add(d);
    requestMappingHandlerAdapter.setMessageConverters(messageConverters);
    return requestMappingHandlerAdapter;
}

Test class:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {ControllerIntegrationUnitTestContext.class})
@WebAppConfiguration
public class SampleUnitTest {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext webAppContext;
@Before
public void setUp() {
    mockMvc = MockMvcBuilders.webAppContextSetup(webAppContext).build();
}
@Test
public void testrun() throws Exception{
    mockMvc.perform(get("/user/isloggedin").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andExpect(content().string("true"));
}}

and the error i am getting when running the test:

  2014-06-04 20:54:15,911 [DEBUG] [FrameworkServlet,initWebApplicationContext(),558] - Published WebApplicationContext of servlet '' as ServletContext attribute with name [org.springframework.web.servlet.FrameworkServlet.CONTEXT.]
    2014-06-04 20:54:15,911 [INFO] [FrameworkServlet,initServletBean(),498] - FrameworkServlet '': initialization completed in 151 ms
    2014-06-04 20:54:15,911 [DEBUG] [HttpServletBean,init(),139] - Servlet '' configured successfully
  2014-06-04 20:54:15,933 [DEBUG] [DispatcherServlet,doService(),838] - DispatcherServlet with name '' processing GET request for [/user/isloggedin]
  2014-06-04 20:54:15,937 [DEBUG] [AbstractUrlHandlerMapping,getHandlerInternal(),124] - Mapping [/user/isloggedin] to HandlerExecutionChain with handler [X.Y.Z.controllers.UserController@17da0d1] and 1 interceptor
  2014-06-04 20:54:15,939 [DEBUG] [DispatcherServlet,doDispatch(),925] - Last-Modified value for [/user/isloggedin] is: -1
  2014-06-04 20:54:15,945 [DEBUG] [HandlerMethodInvoker,invokeHandlerMethod(),172] - Invoking request handler method: public X.Y.Z.webresources.ServerResponse X.Y.Z.controllers.UserController.isloggedin()
   2014-06-04 20:54:15,949 [DEBUG] [AbstractHandlerExceptionResolver,resolveException(),134] - Resolving exception from handler [X.Y.Z.controllers.UserController@17da0d1]: org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
   2014-06-04 20:54:15,950 [DEBUG] [AbstractHandlerExceptionResolver,resolveException(),134] - Resolving exception from handler [X.Y.Z.controllers.UserController@17da0d1]: org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
    2014-06-04 20:54:15,950 [DEBUG] [AbstractHandlerExceptionResolver,resolveException(),134] - Resolving exception from handler [X.Y.Z.UserController@17da0d1]: org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
    2014-06-04 20:54:15,950 [DEBUG] [DispatcherServlet,processDispatchResult(),1012] - Null ModelAndView returned to DispatcherServlet with name '': assuming HandlerAdapter completed request handling
    2014-06-04 20:54:15,950 [DEBUG] [FrameworkServlet,processRequest(),991] - Successfully completed request
    2014-06-04 20:54:15,953 [DEBUG] [DirtiesContextTestExecutionListener,afterTestMethod(),94] - After test method: context [DefaultTestContext@12cf9bd testClass = SampleUnitTest, testInstance = context.SampleUnitTest@1c012fa, testMethod = testrun@SampleUnitTest, testException = java.lang.AssertionError: Status expected:<200> but was:<406>, mergedContextConfiguration = [WebMergedContextConfiguration@14c92a7 testClass = SampleUnitTest, locations = '{}', classes = '{class context.ControllerIntegrationUnitTestContext}', contextInitializerClasses = '[]', activeProfiles = '{}', resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.test.context.web.WebDelegatingSmartContextLoader', parent = [null]]], class dirties context [false], class mode [null], method dirties context [false].
   2014-06-04 20:54:15,954 [DEBUG] [ServletTestExecutionListener,afterTestMethod(),138] - Resetting RequestContextHolder for test context [DefaultTestContext@12cf9bd testClass = SampleUnitTest, testInstance = context.SampleUnitTest@1c012fa, testMethod = testrun@SampleUnitTest, testException = java.lang.AssertionError: Status expected:<200> but was:<406>, mergedContextConfiguration = [WebMergedContextConfiguration@14c92a7 testClass = SampleUnitTest, locations = '{}', classes = '{class context.ControllerIntegrationUnitTestContext}', contextInitializerClasses = '[]', activeProfiles = '{}', resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.test.context.web.WebDelegatingSmartContextLoader', parent = [null]]].
    2014-06-04 20:54:15,957 [DEBUG] [DirtiesContextTestExecutionListener,afterTestClass(),126] - After test class: context [DefaultTestContext@12cf9bd testClass = SampleUnitTest, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@14c92a7 testClass = SampleUnitTest, locations = '{}', classes = '{class context.ControllerIntegrationUnitTestContext}', contextInitializerClasses = '[]', activeProfiles = '{}', resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.test.context.web.WebDelegatingSmartContextLoader', parent = [null]]], dirtiesContext [false].
    2014-06-04 20:54:15,958 [INFO] [AbstractApplicationContext,doClose(),873] - Closing org.springframework.web.context.support.GenericWebApplicationContext@9b46a8: startup date [Wed Jun 04 20:54:15 IDT 2014]; root of context hierarchy
     2014-06-04 20:54:15,958 [DEBUG] [AbstractBeanFactory,doGetBean(),249] - Returning cached instance of singleton bean 'lifecycleProcessor'

I am kind of stuck with this and dont know what more to do to make this work

Progress:

the RequestMappingHandlerAdapter was not in context, now it is. but i am getting a

 java.lang.IllegalStateException: Failed to load ApplicationContext
   ...     
  Caused by: java.lang.ClassNotFoundException: com.fasterxml.jackson.core.JsonProcessingException
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)

Progress

updated jackson version, now everything works fine.

Gleeb
  • 10,773
  • 26
  • 92
  • 135
  • See if any of the answers to [this question](http://stackoverflow.com/questions/7462202) help. It covers most if not all of the causes of a 406 using Jackson. – kdgregory Jun 04 '14 at 18:31
  • A quick debug step is to remove the `produces` from your request mapping, and see if you still get the error. – kdgregory Jun 04 '14 at 18:32

1 Answers1

3

Your handler is mapped with

@RequestMapping(value = "isloggedin",method = RequestMethod.GET, produces = "application/json")

It produces application/json. For this to work, your client must Accept application/json. Currently your MockMvc request does not specify such an Accept header. Add one.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • exactly the same: java.lang.AssertionError: Status expected:<200> but was:<406 – Gleeb Jun 04 '14 at 18:16
  • @Gleeb Put a log message in your handler method. Does it get printed? Instead of creating a custom `RequestMappingHandlerAdapter`, try using the default one but configuring your message converters with the `configureCustomMessageConverters` method (or whatever it's called) of the `WebMvcConfigurationSupport` class. – Sotirios Delimanolis Jun 04 '14 at 18:22
  • OK apparently the RequestMappingHandlerAdapter bean was not in the context. but now that it is. i am getting the following. java.lang.ClassNotFoundException: com.fasterxml.jackson.core.JsonProcessingException and i have all the dependencies for jackson. – Gleeb Jun 04 '14 at 18:34
  • 1
    @Gleeb `MappingJackson2HttpMessageConverter` requires Jackson 2. Do you have Jackson 1 or 2? Double check those dependencies. – Sotirios Delimanolis Jun 04 '14 at 18:36