简体   繁体   English

在 Spring Boot 应用程序中测试 websocket

[英]Test websocket in spring boot application

I don't understand how properly write a test case for websocket in springboot application.我不明白如何在springboot应用程序中正确地为websocket编写测试用例。 I have a class that implement WebSocketHandler and I add this handler in WebSocketConfigurer :我有一个实现WebSocketHandler的类,我在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异常: javax.websocket.DeploymentException :发起WebSocket连接的HTTP请求失败

I read that if I set ws://127.0.0.1:8080/test/ (slash on end) it will work , but it doesn't work.我读到如果我设置ws://127.0.0.1:8080/test/ (斜线结尾)它会起作用,但它不起作用。

What I did wrong?我做错了什么?

I found solution:我找到了解决方案:

add annotation @WebIntegrationTest(value = 8080) or you can specify randomPort = true添加注释@WebIntegrationTest(value = 8080)或者您可以指定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() );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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