Test websocket in spring boot application

dzrkot picture dzrkot · Jun 18, 2016 · Viewed 7.8k times · Source

I don't understand how properly write a test case for websocket in springboot application. I have a class that implement WebSocketHandler and I add this handler in WebSocketConfigurer:

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
    registry.addHandler(logWebSocketHandler() , "/test")
            .addInterceptors(new HttpSessionHandshakeInterceptor())
            .setAllowedOrigins("*");
}

@Bean
public LogWebSocketHandler logWebSocketHandler(){
    return new LogWebSocketHandler();
}
}

But when I write this below test case I get an exception:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration({App.class})
@WebAppConfiguration
public class LogsControllerTest  {

private WebSocketContainer container;

@Before
public void setup() {
    container = ContainerProvider.getWebSocketContainer();

}

@Test
public void testGetLog() throws Exception {
    Session session = container.connectToServer(new TestEndpoint(),
            URI.create("ws://127.0.0.1:8080/test"));
}
}

exception: javax.websocket.DeploymentException: The HTTP request to initiate the WebSocket connection failed

I read that if I set ws://127.0.0.1:8080/test/ (slash on end) it will work , but it doesn't work.

What I did wrong?

Answer

dzrkot picture dzrkot · Aug 11, 2016

I found solution:

add annotation @WebIntegrationTest(value = 8080) or you can specify randomPort = true

after that add:

@ClientEndpoint
public class TestWebSocketClient {
    Session session;

    @OnOpen
    public void onOpen(final Session session){
        this.session = session;
    }
}

and at the body of the test:

@Autowired
private LogWebSocketHandler socketHandler;

private WebSocketContainer container;
private TestWebSocketClient client;

@Before
public void setup() {
    container = ContainerProvider.getWebSocketContainer();
    client = new TestWebSocketClient();
}

@Test
public void createSessionAfterOpenLogWebSocketHandler() throws Exception {
    container.connectToServer(client , URI.create("ws://localhost:8080/path"));
    while( !socketHandler.isOpen()){
        // sometime it is doesn't work, but I dont know solution of this problem
        // wait until socket is open
    }
    Assert.assertTrue( socketHandler.isOpen() );
}