问题描述
我有一个带有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()
这为我解决了问题