首页 > 解决方案 > 使用验收测试中的自定义对象调用 REST 端点

问题描述

我将 CucumberGiven中的自定义对象发布到 Rest Controller 中的端点。问题是,据我一直在调查,没有BodyPublisher自定义对象,不建议实施。所以:

代码:

我有以下给定:

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;
    }
}

标签: javaspring-bootrestcucumberacceptance-testing

解决方案


我已经设法使用库 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>

推荐阅读