首页 > 解决方案 > 使用放心框架测试服务器发送事件

问题描述

我正在使用 Spring Boot 并放心测试我的 REST 服务

我有一个休息控制器,例如

@GetMapping(produces = MediaType.TEXT_EVENT_STREAM_VALUE)
Flux<String> getFlux() {
...

如何正确断言响应正文?

我认为该值以“数据:”的形式返回,用于在一次输出后终止的流。

我也不知道在尝试异步影响数据时如何测试流的实际工作?

标签: spring-bootreactive-programmingrest-assured

解决方案


反应测试

您应该使用 WebTestClient 来测试您的反应式服务。

这是一个例子

服务方式:

public Flux<GithubRepo> listGithubRepositories(String username, String token) {
     return webClient.get()
            .uri("/user/repos")
            .header("Authorization", "Basic " + Base64Utils
                    .encodeToString((username + ":" + token).getBytes(UTF_8)))
            .retrieve()
            .bodyToFlux(GithubRepo.class);
}

考试:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class WebclientDemoApplicationTests {

    @Autowired
    private WebTestClient webTestClient;

     @Test
    public void test2GetAllGithubRepositories() {
        webTestClient.get().uri("/api/repos")
                .accept(MediaType.APPLICATION_JSON_UTF8)
                .exchange()
                .expectStatus().isOk()
                .expectHeader().contentType(MediaType.APPLICATION_JSON_UTF8)
                .expectBodyList(GithubRepo.class);
    }

}

请在此处找到示例https://www.callicoder.com/spring-5-reactive-webclient-webtestclient-examples/

标准 MVC 测试

模拟MVC

您可以使用模拟环境来测试控制器类,而无需真正启动 servlet 容器:

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class MockMvcExampleTests {

    @Autowired
    private MockMvc mvc;

    @Test
    public void exampleTest() throws Exception {
        this.mvc.perform(get("/")).andExpect(status().isOk())
                .andExpect(content().string("Hello World"));
    }

}

使用正在运行的服务器:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class RandomPortTestRestTemplateExampleTests {

    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    public void exampleTest() {
        String body = this.restTemplate.getForObject("/", String.class);
        assertThat(body).isEqualTo("Hello World");
    }

}

请阅读官方文档中有关 Spring Boot 测试的更多信息

https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-testing


推荐阅读