微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用protobuf for controller进行Java单元测试?

如何解决如何使用protobuf for controller进行Java单元测试?

我有一个带有requestBody和responseBody的protobuf弹簧启动控制器。如下所示:

@RequestMapping(value = "/position/open",produces = "application/x-protobuf")
@ResponseBody
public MsgProto.Response positionopen(@RequestBody MsgProto.Request request)throws Exception {
    log.info("start /position/open");
    return orderPositionService.addOrder(request);
}

现在,我想使用 mockmvc 进行单元测试以测试控制器,但是每次都失败。我相信下面的代码 protobuf 发出HTTP请求是错误的,知道如何解决该问题吗?

mockmvc.perform(post("/position/open").contentType("application/x-protobuf")
            .content(ObjectsMock.mockMsgProtoRequest().toByteArray())).andDo(print())
            .andExpect(status().isOk());

例外:

Resolved Exception:
         Type = org.springframework.web.HttpMediaTypeNotSupportedException
MockHttpServletResponse:
       Status = 415
Error message = null
      Headers = [Accept:"application/json,application/octet-stream,application/xml,application/*+json,text/plain,text/xml,application/x-www- 
form-urlencoded,application/*+xml,multipart/form-data,multipart/mixed,*/*"]

解决方法

我假设auto& someMap = *(tmap.get()); // get the reference to the map instead of copy. try { // either use reference to be able to modify the non-const map // or use the "at" api to access the element without [] operator. cout << someMap[1] << tmap->at(2); } catch (const std::out_of_range& oor) { cout << "Out of Range error: " << oor.what() << endl; } 在这里缺失。没有此特定的转换器,Spring MVC无法读取/写入任何消息。

您可以按以下方式创建它:

ProtobufHttpMessageConverter

接下来,请确保将HTTP方法添加到您的方法中,因为我假设(通过阅读测试)您希望它是HTTP POST处理程序。您还可以添加@Bean public ProtobufHttpMessageConverter protobufHttpMessageConverter() { return new ProtobufHttpMessageConverter(); } 属性,以声明此端点也消耗了Protobuf。

consumes

除此之外,还有一个article on the Spring blog available涵盖了您的用例,并介绍了如何在Spring MVC中使用Protobuf。

,

您需要将 Protobuf 转换器添加到 MockMvc builder

MockMvcBuilders.standaloneSetup(controller)
               .setMessageConverters(new ProtobufHttpMessageConverter())
               .build()

这为我解决了问题

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。