简体   繁体   中英

Test websocket in spring boot application

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?

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() );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM