java - 运行 JUnit/Mockito 测试时出现 org.springframework.http.converter.HttpMessageNotReadableException

标签 java spring spring-boot junit mockito

我正在我的 Spring Boot 应用程序中使用 Mockito 运行 JUnit 测试。我正在 mock Controller 应该调用的存储库。当使用响应代码 400 运行 POST 测试时,我收到 HttpMessageNotReadableException(GET 工作正常)。

package coffee;

import static org.junit.Assert.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import java.util.*;

import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

import coffee.controller.AboutController;
import coffee.data.AboutRepository;

@RunWith(SpringRunner.class)
@WebMvcTest(value = AboutController.class, secure = false)
public class AboutControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private AboutRepository aboutRepository;

    List<About> res;

    @Before
    public void setUp() {
        res = new ArrayList<About>();
        About about = new About();
        about.setName("Test");
        res.add(about);
    }

    @Test
    public void postAbouts() throws Exception{
        About about = res.get(0);

        Mockito.when(aboutRepository.save(about))
            .thenReturn(about);

        RequestBuilder requestBuilder = MockMvcRequestBuilders.post("/abouts")
                .accept(MediaType.APPLICATION_JSON)
                .contentType(MediaType.APPLICATION_JSON)
                .content("{'id':null,'position':null,'name':'Test','description':null,'image':null}");

        MvcResult result = mockMvc.perform(requestBuilder)
            .andExpect(status().isOk())
            .andReturn();

        JSONAssert.assertEquals("{'id':null,'position':null,'name':'Test','description':null,'image':null}", 
                result.getResponse().getContentAsString(),
                false);
    }
}
<小时/>
    MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /abouts
       Parameters = {}
          Headers = {Content-Type=[application/json], Accept=[application/json]}
             Body = <no character encoding set>
    Session Attrs = {}

Handler:
             Type = coffee.controller.AboutController
           Method = public coffee.About coffee.controller.AboutController.postAbout(coffee.About)

Async:
    Async started = false
     Async result = null

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

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 400
    Error message = null
          Headers = {}
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []
2019-05-21 14:47:56.035  INFO 1977 --- [       Thread-4] o.s.w.c.s.GenericWebApplicationContext   : Closing org.springframework.web.context.support.GenericWebApplicationContext@7fd50002: startup date [Tue May 21 14:47:54 PDT 2019]; root of context hierarchy

这是正在测试的 Controller

package coffee.controller;

import coffee.*;
import coffee.data.AboutRepository;

import java.util.Optional;

import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;



@RestController
@RequestMapping(path="abouts",
                produces="application/json",
                consumes="application/json")
@CrossOrigin(origins="*")
public class AboutController {

    private AboutRepository aboutRepo;

    public AboutController(AboutRepository aboutRepo) {
        this.aboutRepo = aboutRepo;
    }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public About postAbout(@RequestBody About about) {
        return aboutRepo.save(about);
    }

}

最佳答案

关于 json 似乎无效。您可以尝试在内容方法上使用带双引号的 json 吗?

{ "id":null, "position":null, "name":"Test", "description":null, "image":null }

关于java - 运行 JUnit/Mockito 测试时出现 org.springframework.http.converter.HttpMessageNotReadableException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56246445/

相关文章:

java - JPanel 调整大小显示另一个 JPanel

java - mvn 包因新的 SpringBoot 项目而失败

java - 在 VSCode 中更改 java 项目源?

java - 如何在 Spring Boot 中处理 DeferredResult 中的异常?

java - Springfox/Swagger 不解析多态字段

java - 您能推荐任何可嵌入的 Javascript 引擎吗?

java - 从 ColdFusion 访问 mp3agic

java - 如何使用 XPages Java 代码在自定义控件中设置输入控件的有效方法?

java - 如何从 jar 文件加载 Spring 上下文 xml

java - Springboot 1.4/单元测试时出错(hibernate AttributeConverter 注册多次)