Test websocket in spring boot application
Asked Answered
G

1

9

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?

Gaeta answered 18/6, 2016 at 16:36 Comment(0)
G
7

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() );
}
Gaeta answered 11/8, 2016 at 10:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.