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?
You can use the WebTestClient on Spring Framework 5.0 or later.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With