I'm trying to test WebSockets in SpringBoot application, however it is not working. Subscriber
that should capture incoming message is not doing it.
@Configuration
@EnableWebSocketMessageBroker
internal class WsConfig : WebSocketMessageBrokerConfigurer {
override fun configureMessageBroker(config: MessageBrokerRegistry) {
config.enableSimpleBroker("/queue")
config.setApplicationDestinationPrefixes("/app")
}
override fun registerStompEndpoints(registry: StompEndpointRegistry) {
registry.addEndpoint("/ws").withSockJS()
}
}
@Controller
class WsController(private val messagingTemplate: SimpMessagingTemplate) {
@MessageMapping("/chat")
fun sendChatMessage(@Payload message: String) = messagingTemplate.convertAndSend("/queue/chat", message)
}
And the test itself.
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class WsTest(@LocalServerPort private val port: Int) {
private val wsClient = createWebSocketClient()
private val lock = CountDownLatch(1)
@Test
fun test1() {
val subscriber = connect()
val publisher = connect()
val capturedMessages = mutableListOf<String>()
subscriber.subscribe("/queue/chat", frameHandler(capturedMessages))
publisher.send("/app/chat", "lorem ipsum")
lock.await(5, TimeUnit.SECONDS)
Assertions.assertEquals(1, capturedMessages.size)
}
private fun createWebSocketClient(): WebSocketStompClient {
val webSocketClient = WebSocketStompClient(SockJsClient(listOf(WebSocketTransport(StandardWebSocketClient()))))
webSocketClient.messageConverter = MappingJackson2MessageConverter()
return webSocketClient
}
private fun connect() = wsClient.connect("ws://localhost:$port/ws", object : StompSessionHandlerAdapter() {}).get(2, TimeUnit.SECONDS)
private fun frameHandler(messages: MutableList<String>) =
object : StompSessionHandlerAdapter() {
override fun getPayloadType(headers: StompHeaders): Type {
return String::class.java
}
override fun handleFrame(headers: StompHeaders, payload: Any?) {
messages.add(payload as String)
}
}
}
Long story short, handleFrame()
is not beeing called at all and I'm out of ideas why is that happening.
Aucun commentaire:
Enregistrer un commentaire