MockMvc POST Junit测试返回HttpMessageNotReadableException

时间:2015-03-02 10:27:04

标签: java json spring-mvc junit mockmvc

目前正在使用MockMVC编写单元测试以测试我的控制器。 控制器本身工作正常,但我正在努力创建一个测试来证明这一点。

下面我创建了一个简化示例来重新创建问题。

MyController

@RestController
@RequestMapping(value = "/controller")
public class TestController {

private final Logger LOG = LoggerFactory.getLogger(this.getClass());

/**
 * Resets the system including re-creation of the actor system and reload of
 * application configuration
 *
 * @param testObject
 * @return
 */
@RequestMapping(value = "/testPost", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.OK)
public void test(@RequestBody TestObject testObject) {


}

我的测试

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = {TestController.class})
public class TestControllerTest {

private MockMvc mockMvc;
private final static ObjectMapper MAPPER = new ObjectMapper();

public TestControllerTest() {

}

@Test
public void testJSONPost() throws Exception {

    mockMvc = MockMvcBuilders.standaloneSetup(new TestController()).setMessageConverters(new MappingJackson2HttpMessageConverter()).alwaysDo(print()).build();
    mockMvc.perform(post("/controller/testPost").content(MAPPER.writeValueAsString(new TestObject(Long.MIN_VALUE, "value")))
            .contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk());
}

当测试运行时,我得到400响应。你能提供的任何见解都会带来好处,谢谢。

0 个答案:

没有答案