我正在尝试为端点编写单元测试。
此端点应采用如下所示的 json 对象
@PostMapping(value = "/test")
public String endPoint(@RequestBody String obj) {
try {
JSONObject inputJsonObject = new JSONObject(individualJson);
} catch (JSONException | IOException e) {
throw new MyException("JSONObject not valid");
}
......
}
在我的单元测试中,我尝试发送一个空字符串,并且希望出现 JSONException
mvc.perform(post(url)
.contentType(MediaType.APPLICATION_JSON)
.content(""))
.andReturn().getResponse();
但是我的帖子没有达到我的端点...就像它无法将空字符串评估为字符串:“”没有达到端点 “”(带空格)正在到达终点...
这是调用返回的异常:
org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public com.ba.mypackage.MyController.endPoint(java.lang.String)
如何通过传递空字符串“”来访问端点?
最佳答案
不能,因为发送空字符串作为正文与在此上下文中不发送正文是一样的,并且 @RequestBody
注释不允许不发送正文,因为默认值因为其 required
属性为 true
。
发送空字符串作为正文与不发送正文是一样的,因为在 HTTP 中,POST 请求具有由 CRLF 分隔的 header 部分和正文部分,并且在有正文和没有正文时都需要分隔 CRLF 。 HTTP 规范中是这样定义的,参见 https://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html详情:
5 Request
A request message from a client to a server includes, within the first line of that message, the method to be applied to the resource, the identifier of the resource, and the protocol version in use.
Request = Request-Line ; Section 5.1
*(( general-header ; Section 4.5
| request-header ; Section 5.3
| entity-header ) CRLF) ; Section 7.1
CRLF
[ message-body ] ; Section 4.3
您提供的标题部分,正文是您希望作为空字符串的内容。但是,您无论如何都需要使用 CRLF,因此请求将如下所示:
POST /url HTTP/1.1
Content-Type: application/json; charset=UTF-8
Accept: application/json, application/javascript, text/javascript
Content-Length: 0
Host: localhost:8888
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.5.3 (Java/1.8.0_112)
Accept-Encoding: gzip,deflate
或者,将 [CRLF] 放在该字符所在的位置,
POST /url HTTP/1.1[CRLF]
Content-Type: application/json; charset=UTF-8[CRLF]
Accept: application/json, application/javascript, text/javascript[CRLF]
Content-Length: 0[CRLF]
Host: localhost:8888[CRLF]
Connection: Keep-Alive[CRLF]
User-Agent: Apache-HttpClient/4.5.3 (Java/1.8.0_112)[CRLF]
Accept-Encoding: gzip,deflate[CRLF]
[CRLF]
由于内容长度为零并且 CRLF 分隔符需要始终存在,因此如何区分作为正文发送的空字符串和根本不发送正文?问题是你不能,在这种情况下这是同一件事,所以你要求的事情无法完成。
关于java - 发送空字符串作为 RequestBody 未命中 Rest 端点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52771959/