PaulJ
PaulJ

Reputation: 1510

Testing Server Sent Event With Rest Assured Framework

I am using spring boot and rest assured to test my REST services

I have a rest controller, such as

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

How do I assert on the response body correctly?

I think the value comes back as "data: " for a stream that terminates after one output.

I also have no idea how to test a stream actual works when trying to affect the data asynchronously?

Upvotes: 3

Views: 1887

Answers (1)

Simon Martinelli
Simon Martinelli

Reputation: 36123

Reactive Testing

You should use WebTestClient to test your reactive services.

Here is an example

The service method:

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

The Test:

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

}

Please find the examples here https://www.callicoder.com/spring-5-reactive-webclient-webtestclient-examples/

Standard MVC Testing

MockMVC

You could use a mock environment where the controller classes are tested without really launching a servlet container:

@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"));
    }

}

With a running server:

@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");
    }

}

Please read more about Spring Boot Testing in the official documentation

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

Upvotes: 2

Related Questions