mockMvc POST Junit测试失败,出现HttpMessageNotReadableException

时间:2014-09-30 14:14:03

标签: java spring rest jackson

我正在尝试对我在控制器中创建的帖子请求进行JUNIT测试。虽然GET成功,但POST不会。

public class SampleObject implements Serializable {

    private static final long serialVersionUID = 1L;
    private String name;
    public SampleObject(String name) {
        this.name = name;
    }
    public String getName() {
        return name;
    }
}

样品张贴请求

    @RequestMapping(value = "/post", method = RequestMethod.POST, produces="application/json", consumes="application/json")
    @ResponseBody
    public SampleObject postActiveSource(@RequestBody SampleObject inputObject) {
        return inputObject;
    }

这是我的模拟测试。

public class MockMvcHtmlUnitCreateMessageTest {


MockMvc mockMvc;

@InjectMocks
SampleController controller; 

 @Before
  public void setup() {
    MockitoAnnotations.initMocks(this);

    this.mockMvc = standaloneSetup(controller)
            .setMessageConverters(new MappingJackson2HttpMessageConverter()).build();
  }

@Test
public void test() {

    SampleObject so = controller.new SampleObject("abcd");
    ObjectMapper mapper = new ObjectMapper();


    try {
        this.mockMvc.perform(post("/service/sample/post").content(mapper.writeValueAsString(so)).contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)).andDo(print());

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
 }

}

我得到了这个例外。

Resolved Exception:
          Type = org.springframework.http.converter.HttpMessageNotReadableException

但是,get请求正常。这里出了什么问题?任何帮助将不胜感激。

EDIT1:

我注意到以下异常。这可能有所帮助。

nested exception is com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found for type [simple type, class com..rest.controller.SampleController$SampleObject]: can not instantiate from JSON object (need to add/enable type information?)
 at [Source: org.springframework.mock.web.DelegatingServletInputStream@c792d4; line: 1, column: 2]

EDIT2:

基于a suggestion below,我改变了修改构造函数,

public SampleObject(@JsonProperty("name") String name) {
            this.name = name;
}

然而,我得到以下异常

Caused by: java.lang.IllegalArgumentException: Argument #0 of constructor [constructor for SampleController$SampleObject, annotations: [null]] has no property name annotation; must have name when multiple-paramater constructor annotated as Creator at com.fasterxml.jackson.databind.deser.BasicDeserializerFactory.findValueInstantia‌​tor(BasicDeserializerFactory.java:287) ~[jackson-databind-2.3.4.jar:2.3.4] 

2 个答案:

答案 0 :(得分:2)

杰克逊希望默认情况下为您的POJO类提供无参数构造函数。如果需要参数化构造函数,则需要注释其参数。

public SampleObject(@JsonProperty("name") String name) {
    this.name = name;
}

答案 1 :(得分:0)

您可能必须在配置文件中配置MessageConverter。如果您使用Java配置:

 protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(Include.NON_NULL);

        MappingJackson2HttpMessageConverter jacksonConverter = new MappingJackson2HttpMessageConverter();
        jacksonConverter.setObjectMapper(mapper);

        converters.add(jacksonConverter);
    }