简体   繁体   English

mockMvc POST Junit测试失败,并带有HttpMessageNotReadableException

[英]mockMvc POST Junit test failing with HttpMessageNotReadableException

I am trying to do a JUNIT test for a post request I have created in a controller. 我正在尝试对我在控制器中创建的发布请求进行JUNIT测试。 While GET succeeds, POST does not. 尽管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;
    }
}

Sample post request 样品要求

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

And here is my mock test. 这是我的模拟测试。

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();
    }
 }

}

I get the this exception. 我得到这个例外。

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

However, a get request works fine. 但是,获取请求的效果很好。 What is going wrong here? 这是怎么了? Any help would be appreciated. 任何帮助,将不胜感激。

Edit1: 编辑1:

I noticed the following exception. 我注意到以下异常。 This might help. 这可能会有所帮助。

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: 编辑2:

Based on a suggestion below , I changed modified the constructor, 根据以下建议 ,我更改了构造函数,

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

however, I get the following exception 但是,我得到以下异常

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] 

Jackson expects a parameterless constructor for your POJO classes by default. 杰克逊默认情况下需要POJO类的无参数构造函数。 If you need to have a parameterized constructor, you'll need to annotated its parameters. 如果需要使用参数化的构造函数,则需要注释其参数。

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

You might have to configure MessageConverter in your config file. 您可能必须在配置文件中配置MessageConverter If you use Java Configuration: 如果使用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);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM