以下是一个使用Spring Boot WebClient的测试用例示例:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class WebClientTest {

    @Autowired
    private WebClient webClient;

    @Test
    void testGet() {
        Mono<String> result = webClient.get()
                .uri("https://jsonplaceholder.typicode.com/todos/1")
                .retrieve()
                .bodyToMono(String.class);

        StepVerifier.create(result)
                .expectNextMatches(response -> response.contains("\"userId\": 1"))
                .expectComplete()
                .verify();
    }

    @Test
    void testPost() {
        Todo todo = new Todo();
        todo.setUserId(1);
        todo.setTitle("Test Todo");
        todo.setCompleted(false);

        Mono<Todo> result = webClient.post()
                .uri("https://jsonplaceholder.typicode.com/todos")
                .contentType(MediaType.APPLICATION_JSON)
                .body(Mono.just(todo), Todo.class)
                .retrieve()
                .bodyToMono(Todo.class);

        StepVerifier.create(result)
                .expectNextMatches(response -> response.getId() != null && response.getTitle().equals("Test Todo"))
                .expectComplete()
                .verify();
    }
}

此示例使用JSONPlaceholder API作为测试目标。testGet()方法使用webClient.get()方法从API获取一个TODO,然后使用StepVerifier进行响应测试。testPost()方法使用webClient.post()方法将一个TODO对象发送到API,然后使用StepVerifier进行响应测试。

请注意,此测试需要启动Spring Boot应用程序,并使用@SpringBootTest注释进行配置。它还需要WebClient bean的自动装配

springboot WebClient 测试用例

原文地址: https://www.cveoy.top/t/topic/cFAK 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录