在spring boot应用程序中测试websocket

时间:2016-06-18 16:36:03

标签: java spring spring-boot spring-websocket java-websocket

我不明白在 springboot 应用程序中如何正确编写 websocket 的测试用例。我有一个实现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();
}
}

但是当我在测试用例下面写这个时,我得到一个例外:

@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"));
}
}

异常: javax.websocket.DeploymentException:启动WebSocket连接的HTTP请求失败

我读到如果我设置ws://127.0.0.1:8080/test/(结尾为斜线)它会起作用,但它不起作用。

我做错了什么?

1 个答案:

答案 0 :(得分:1)

我找到了解决方案:

添加注释@WebIntegrationTest(value = 8080)或您可以指定randomPort = true

之后添加:

@ClientEndpoint
public class TestWebSocketClient {
    Session session;

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

并且在测试的主体上:

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