Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test server sent events with Spring?

I've implemented a controller with a method returning an SseEmitter and now I want to test it. The only way I could find so far is the following:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {SsePaymentReceivedController.class, AutomatBackendContextInitializer.class, EventBusImpl.class})
@WebAppConfiguration
public class SsePaymentReceivedControllerIntegrationTest {

@Inject
WebApplicationContext context;
@Inject
SsePaymentReceivedController sseCoinController;
@Inject
EventBusImpl eventBus;

MockMvc mockMvc;

@Before
public void setUpMockMvc() {
    this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build();
}

@Test
public void subscriptionToSseChannelIsFine() throws Exception {
    MvcResult result = mockMvc.perform(get("/sse/payment"))
            .andExpect(status().isOk())
            .andReturn();
    eventBus.fireNotification(new PaymentReceivedNotification("50", Currency.EURO));
    LinkedHashSet<ResponseBodyEmitter.DataWithMediaType> emitters =
            (LinkedHashSet<ResponseBodyEmitter.DataWithMediaType>)Whitebox.getInternalState(((SseEmitter)result.getModelAndView().getModel().get("sseEmitter")), "earlySendAttempts");
    final Iterator<ResponseBodyEmitter.DataWithMediaType> iterator = emitters.iterator();

    ResponseBodyEmitter.DataWithMediaType dataField = iterator.next();
    assertEquals("data:", dataField.getData());

    ResponseBodyEmitter.DataWithMediaType valueField = iterator.next();
    assertEquals("{\"remainingAmount\":\"50\",\"currency\":\"EURO\"}", valueField.getData());

    ResponseBodyEmitter.DataWithMediaType lastField = iterator.next();
    assertEquals("\n\n", lastField.getData());
}
}

There must be an approach better than inspecting the internals of the returned model and I'm looking for that - any ideas?

like image 508
Andras Hatvani Avatar asked Feb 19 '16 07:02

Andras Hatvani


1 Answers

You can use the WebTestClient on Spring Framework 5.0 or later.

like image 182
Rossen Stoyanchev Avatar answered Oct 16 '22 20:10

Rossen Stoyanchev