gpt4 book ai didi

java - 在 spring boot 应用程序中测试 websocket

转载 作者:行者123 更新时间:2023-11-30 10:43:04 24 4
gpt4 key购买 nike

我不明白如何在 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/(末尾的斜杠)它会起作用,但它不起作用。

我做错了什么?

最佳答案

我找到了解决方案:

添加注释 @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() );
}

关于java - 在 spring boot 应用程序中测试 websocket,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37899268/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com