如何使用RestAssured编写向application/json型Spring Boot REST API传PDF的测试
解决方案
场景1:接口明确要求JSON格式请求体
这种场景下需要将PDF文件编码为Base64字符串后作为JSON的字段传输,同时你要求的PDF魔数校验可以在读取文件后直接实现:
import java.nio.file.Files; import java.nio.file.Paths; import java.util.Base64; // 你可以用任意自己常用的JSON工具 import com.alibaba.fastjson.JSONObject; // 读取PDF文件 Path pdfPath = Paths.get("src","test","resources", "test.pdf"); byte[] fileBytes = Files.readAllBytes(pdfPath); // PDF魔数校验:合法PDF前两个字节为0x25、0x50,对应ASCII字符"%P" if (fileBytes.length < 2 || fileBytes[0] != 0x25 || fileBytes[1] != 0x50) { throw new IllegalArgumentException("待上传文件不是合法PDF格式"); } // 转Base64字符串 String pdfBase64Content = Base64.getEncoder().encodeToString(fileBytes); // 组装JSON请求体 JSONObject requestJson = new JSONObject(); requestJson.put("pdfFile", pdfBase64Content); // 其他请求参数按接口要求正常添加即可
RestAssured请求写法和你原有逻辑保持一致即可:
given() .header(X_MOCK_ID, mockId.toString()) .header("Content-Type", "application/json") .body(requestJson.toJSONString()) .when() .put("/v1/customer/messages/" + messageId) .then() .assertThat() .statusCode(Response.Status.OK.getStatusCode()) .header(HttpHeaders.CACHE_CONTROL, equalTo("no-cache"));
场景2:接口实际接受二进制文件流(和你贴的图片上传控制器逻辑一致)
如果你的PDF上传接口逻辑和示例的图片控制器一致,是直接读取请求体的输入流存为字节,那不需要传JSON,直接修改Content-Type为application/pdf传输文件字节即可:
given() .header(X_MOCK_ID, mockId.toString()) .header("Content-Type", "application/pdf") .body(fileBytes) // 直接传入读取好的PDF字节数组,也可以直接传File对象 .when() .put("你的PDF上传接口路径") .then() .assertThat() .statusCode(204); // 匹配示例控制器的返回逻辑
之前415报错原因说明
你之前使用multipart/mixed + multiPart的写法仅适用于form-data表单上传文件的场景,和你接口要求的媒体类型不匹配,因此返回415状态码。
内容的提问来源于stack exchange,提问作者Lars Andren
相关产品推荐
相关产品推荐

