Spring Controller集成测试无法解析响应并使用406 HTTP代码使测试失败

时间:2014-06-04 18:07:52

标签: java spring controller jackson integration-testing

我正在尝试为我的控制器进行集成测试,但由于某种原因,测试上下文无法解析响应并导致测试失败,并抛出406个HTTP代码。

我在上下文中有jackson mapper bean。

以下是代码:

控制器:

@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");
}

测试环境:

@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 {}

在WebMvcConfig里面我有:

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

测试类:

@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"));
}}

以及运行测试时出现的错误:

  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'

我有点坚持这个,不知道还有什么可以做这项工作

进度:

RequestMappingHandlerAdapter不在上下文中,现在是。但我得到了一个

 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)

进度

更新了杰克逊版本,现在一切正常。

1 个答案:

答案 0 :(得分:3)

你的处理程序用

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

生成 application/json。为此,您的客户必须Accept application/json。目前,您的MockMvc请求未指定此类Accept标头。添加一个。