Spring MVC集成测试时出现406错误,而该服务在浏览器中运行良好

时间:2014-07-14 06:38:50

标签: spring rest jackson integration-testing

我有一个Spring 4 MVC Web应用程序。我正在为我的REST服务进行集成测试。通过浏览器rest-clients和jquery / restangular UI调用服务也很好。但是,当我运行集成测试时,我收到错误Expected :200 Actual :406

仅当Spring将Object转换为json时才会出现此问题。我尝试通过ObjectMapper进行手动转换并返回结果。在这种情况下,测试开始工作。 这是我的文件:

控制器:

@RequestMapping(value="/permissions", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<Object> getPermissions() throws Exception {
        return new ResponseEntity<Object>(getPermissions(), HttpStatus.OK);
    }

整合测试:

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration({"classpath*:rest-config.xml", "classpath:domain-config.xml"})
public class ITController {

    @Autowired
    private WebApplicationContext context;

    private MockMvc mockMvc;

    @Before
    public void setup() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build();
    }
@Test
    public void getPermissions() throws Exception {
        MvcResult result = this.mockMvc.perform(get("/permissions/4")
                .accept("application/json"))
                .andExpect(status().isOk())
                .andExpect(content().contentType("application/json")).andReturn();
        Permission p = new GsonBuilder().create().fromJson(result.getResponse().getContentAsString(), Permission.class);
        Assert.assertNotNull(p);
    }
}

如果我将以下代码添加到控制器,则测试开始工作。

ObjectMapper mapper = new ObjectMapper();
String stringVal = mapper.writeValueAsString(permission);

我的春季配置文件的一部分:

<mvc:annotation-driven/>

    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="order" value="1"/>
        <property name="messageConverters">
            <list>
                <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                    <property name="supportedMediaTypes" value="application/json"/>
                </bean>
                <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                    <property name="supportedMediaTypes" value="text/plain;charset=UTF-8"/>
                </bean>
            </list>
        </property>
    </bean>

我在我的申请中使用jackson version 2.2.1

DEBUG Log

2014-07-14 14:41:37 DEBUG EntityPrinter:121 - com.myapp.entity.Permission{isActive=true, description=permission, id=4, Name=mypermission}
2014-07-14 14:41:37 DEBUG JdbcTransaction:113 - committed JDBC Connection
2014-07-14 14:41:37 DEBUG JdbcTransaction:126 - re-enabling autocommit
2014-07-14 14:41:37 DEBUG LogicalConnectionImpl:314 - Releasing JDBC connection
2014-07-14 14:41:37 DEBUG LogicalConnectionImpl:332 - Released JDBC connection
2014-07-14 14:41:37 DEBUG ConnectionProxyHandler:219 - HHH000163: Logical connection releasing its physical connection

0 个答案:

没有答案