java - 使用验收测试中的自定义对象调用 REST 端点
问题描述
我将 CucumberGiven
中的自定义对象发布到 Rest Controller 中的端点。问题是,据我一直在调查,没有BodyPublisher
自定义对象,不建议实施。所以:
- 该方法
createMessage
可以接收自定义对象(Message
)还是 只接收一个Map
或更简单的结构?(以本机方式使用自定义对象调用端点似乎不自然)
代码:
我有以下给定:
Given("^we have called the messages endpoint with a valid JSON message:$", (final DataTable dataTable) -> {
final var messageRawData = dataTable.asLists(String.class).stream()
.collect(toMap(row -> row.get(0), row -> row.get(1)));
final var faceString = messageRawData.keySet().toArray()[1].toString();
final var body = messageRawData.get(faceString).toString();
final var message = new Message(Face.valueOf(faceString), body);
final var messageBodyPublisher = HttpRequest.BodyPublishers.ofString(
new ObjectMapper().writeValueAsString(messageRawData));
final var request = newBuilder(
create("http://localhost:" + applicationPort + "/message"))
.header("Content-Type", MediaType.APPLICATION_JSON_VALUE)
.POST(messageBodyPublisher).build();
assertThat(newHttpClient().send(request, ofString()).statusCode(), is(200));
});
}
这实际上达到了以下端点:
@PostMapping(value = "/message", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Message> createMessage(@RequestBody final Message message) {
return ResponseEntity.ok(this.messageService.save(message));
}
其中 Message 就是以下 POJO:
public class Message {
private Face face;
private String body;
public Message(final Face face, final String body) {
this.face = face;
this.body = body;
}
}
解决方案
我已经设法使用库 RestAssured 来实现它(使用自定义对象):
When("^we have called the messages endpoint with a valid JSON message:$", (final DataTable dataTable) -> {
final Message message = assembleMessageFromDataTable(dataTable);
response = with().body(message)
.when()
.header("Content-Type", MediaType.APPLICATION_JSON_VALUE)
.request("POST", "http://localhost:" + applicationPort + "/message");
});
Maven依赖:
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>4.4.0</version>
<scope>test</scope>
</dependency>
推荐阅读
- python - 是否可以在 Numpy 矢量化广播操作期间访问当前索引?
- ios - tableView 编辑模式删除按钮(减号)没有响应点击 - 我该如何解决这个问题?
- php - 如何将查询字符串添加到 Laravel 视图
- swift - 如何在两个“地方”获取 Firebase 数据?
- location - 切换 IsFloat 时,QDockWidget 不记得浮动大小和位置
- scala - 如果找不到匹配,则将 findFirstMatchIn 设置为忽略行-spark-scala
- apache-spark - 如何在结构化流中保持和重置状态?
- android - 如何在 AIDE 中使用 Room?
- javascript - 如何在 React 中访问孩子的状态?(反应钩子)
- bitbucket-pipelines - bitbucket 管道部署批准