json - REST POST Controller 说 : Could not read JSON: No content to map due to end-of-input

标签 json rest testing post

我正在针对 REST Controller POST 处理程序进行集成测试。嗯,我正在努力。

它给了我 HttpMessageNotReadableException 异常:无法读取 JSON:由于输入结束没有要映射的内容

这是我的 Controller :

@Controller
@RequestMapping("admin")
public class AdminController {

    private static Logger logger = LoggerFactory.getLogger(AdminController.class);

    private static final String TEMPLATE = "Hello, %s!";

    @Autowired 
    private AdminService adminService;

    @Autowired
    private AdminRepository adminRepository;

    @RequestMapping(value = "crud", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ResponseEntity<Admin> add(@RequestBody Admin admin, UriComponentsBuilder builder) {
        AdminCreatedEvent adminCreatedEvent = adminService.add(new CreateAdminEvent(admin.toEventAdmin()));
        Admin createdAdmin = Admin.fromEventAdmin(adminCreatedEvent.getEventAdmin());
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type", "application/json; charset=utf-8");
        responseHeaders.setLocation(builder.path("/admin/{id}").buildAndExpand(adminCreatedEvent.getAdminId()).toUri());
        return new ResponseEntity<Admin>(createdAdmin, responseHeaders, HttpStatus.CREATED);
    }

    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseBody
    public String handleException(HttpMessageNotReadableException e) {
        return e.getMessage();
    }

}

基础测试类:

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration( classes = { ApplicationConfiguration.class, WebSecurityConfig.class, WebConfiguration.class, WebTestConfiguration.class })
@Transactional
public abstract class AbstractControllerTest {

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Autowired
    private FilterChainProxy springSecurityFilterChain;

    protected MockHttpSession session;

    protected MockHttpServletRequest request;

    protected MockMvc mockMvc;

    @Before
    public void setup() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).addFilters(this.springSecurityFilterChain).build();
    }

}

集成测试:

@Test
public void testAdd() throws Exception {
    HttpHeaders httpHeaders = Common.createAuthenticationHeaders("stephane" + ":" + "mypassword");
    this.mockMvc.perform(
        post("/admin/crud").headers(httpHeaders)
        .param("firstname", "Stephane")
        .param("lastname", "Eybert")
        .param("login", "stephane")
        .param("password", "toto")
    ).andDo(print())
    .andExpect(
        status().isOk()
    ).andReturn();
}

控制台日志必须说的内容:

2013-11-04 19:31:23,168 DEBUG  [HttpSessionSecurityContextRepository] SecurityContext stored to HttpSession: 'org.springframework.security.core.context.SecurityContextImpl@158ddda0: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@158ddda0: Principal: org.springframework.security.core.userdetails.User@552e813c: Username: stephane; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_ADMIN; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Granted Authorities: ROLE_ADMIN'
2013-11-04 19:31:23,168 DEBUG  [RequestResponseBodyMethodProcessor] Written [Could not read JSON: No content to map due to end-of-input
 at [Source: UNKNOWN; line: 1, column: 1]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: No content to map due to end-of-input
 at [Source: UNKNOWN; line: 1, column: 1]] as "application/json;charset=utf-8" using [org.springframework.http.converter.StringHttpMessageConverter@10d328]
2013-11-04 19:31:23,169 DEBUG  [TestDispatcherServlet] Null ModelAndView returned to DispatcherServlet with name '': assuming HandlerAdapter completed request handling
2013-11-04 19:31:23,169 DEBUG  [TestDispatcherServlet] Successfully completed request
2013-11-04 19:31:23,169 DEBUG  [ExceptionTranslationFilter] Chain processed normally
2013-11-04 19:31:23,169 DEBUG  [SecurityContextPersistenceFilter] SecurityContextHolder now cleared, as request processing completed
MockHttpServletRequest:
         HTTP Method = POST
         Request URI = /admin/crud
          Parameters = {firstname=[Stephane], lastname=[Eybert], login=[stephane], password=[toto]}
             Headers = {Content-Type=[application/json], Accept=[application/json], Authorization=[Basic c3RlcGhhbmU6bXlwYXNzd29yZA==]}

             Handler:
                Type = com.thalasoft.learnintouch.rest.controller.AdminController
              Method = public org.springframework.http.ResponseEntity<com.thalasoft.learnintouch.rest.domain.Admin> com.thalasoft.learnintouch.rest.controller.AdminController.add(com.thalasoft.learnintouch.rest.domain.Admin,org.springframework.web.util.UriComponentsBuilder)

               Async:
   Was async started = false
        Async result = null

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

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

            FlashMap:
MockHttpServletResponse:
              Status = 200
       Error message = null
             Headers = {Content-Type=[application/json;charset=utf-8], Content-Length=[254]}
        Content type = application/json;charset=utf-8
                Body = Could not read JSON: No content to map due to end-of-input
 at [Source: UNKNOWN; line: 1, column: 1]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: No content to map due to end-of-input
 at [Source: UNKNOWN; line: 1, column: 1]
       Forwarded URL = null
      Redirected URL = null
             Cookies = []
2013-11-04 19:31:23,177 DEBUG  [TransactionalTestExecutionListener] No method-level @Rollback override: using default rollback [true] for test context [TestContext@ce4625 testClass = AdminControllerTest, testInstance = com.thalasoft.learnintouch.rest.AdminControllerTest@1b62fcd, testMethod = testAdd@AdminControllerTest, testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@9be79a testClass = AdminControllerTest, locations = '{}', classes = '{class com.thalasoft.learnintouch.rest.config.ApplicationConfiguration, class com.thalasoft.learnintouch.rest.config.WebSecurityConfig, class com.thalasoft.learnintouch.rest.config.WebConfiguration, class com.thalasoft.learnintouch.rest.config.WebTestConfiguration}', contextInitializerClasses = '[]', activeProfiles = '{}', resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.test.context.web.WebDelegatingSmartContextLoader', parent = [null]]]

有什么线索吗?

最佳答案

在我看来,问题出在内容格式上。您的端点期望数据将作为 application/json 发送,但在测试中您将其作为 application/x-www-form-urlencoded 发送(无论您在请求中设置正确的内容类型 header )。尝试以 json 格式发送管理对象(作为请求的主体):

{
 "firstname" : "Stephane",
 "lastname" : "Eybert",
 "login" : "stephane",
 "password" : "toto"
}

顺便说一句,/admin/crud 没有闲置 REST 资源寻址规则,您应该将其更改为 /admin。 crud(CREATE、READ、UPDATE、DELETE)将映射到 HTTP 方法(POST、GET、PUT、DELETE)

关于json - REST POST Controller 说 : Could not read JSON: No content to map due to end-of-input,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19775704/

相关文章:

json - Jackson 2 错误地序列化 Java java.nio.file.Path

rest - postman 使用-如何输入参数

json - 如何将外部 JSON 文件加载到 Angular 2 中的测试中?

c# - Visual Studio 2012 伪造 UnitTestIsolation 检测未能初始化

c# - Windows Azure 移动服务和序列化遇到困难

JavaScript从json获取数据到全局变量

android - 改造中的动态路径

使用不同服务类的 Spring Boot 测试

jquery - 如何获取 underscore.js 中的数据项

java - 在 REST 中请求 @pathParam 时,URL 在分号后被截断