【发布时间】:2017-06-20 17:17:26
【问题描述】:
我有一个应用程序公开了 Websocket/SockJS/Stomp 服务器端点,并想运行一个 JUnit 测试,该测试运行客户端(Java STOMP 客户端,也来自 Spring),以测试“发送”功能。
我有一个类似的测试
public void measureSpeedWithWebsocket() throws Exception {
final Waiter subscribeWaiter = new Waiter();
new Thread(() -> {
// Prepare connection
WebsocketClient listener = new WebsocketClient("/mytopic/stomp");
try {
listener.connectAndSubscribe();
subscribeWaiter.resume();
} catch (Exception e) {
e.printStackTrace();
}
}).start();
subscribeWaiter.await(); // Wait for connection.
这里我使用了https://github.com/jhalterman/concurrentunit的Waiter,其作用基本上是延迟测试的主线程,直到辅助线程调用resume()。 这可能是错误的,因为在上下文中运行的 Spring 服务器必须做出反应
我收到以下错误
[INFO ] 2017-02-03 12:36:12.402 [Thread-19] WebsocketClient - Listening
[INFO ] 2017-02-03 12:36:12.403 [Thread-19] WebsocketClient - Connecting to ws://localhost:8083/user...
2017-02-03 12:36:14.097 ERROR 9956 --- [ Thread-19] o.s.w.socket.sockjs.client.SockJsClient : Initial SockJS "Info" request to server failed, url=ws://localhost:8083/user
org.springframework.web.client.ResourceAccessException: I/O error on GET request for "http://localhost:8083/user/info": Connection refused: connect; nested exception is java.net.ConnectException: Connection refused: connect
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:633) ~[spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:595) ~[spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.web.socket.sockjs.client.RestTemplateXhrTransport.executeInfoRequestInternal(RestTemplateXhrTransport.java:138) ~[spring-websocket-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.web.socket.sockjs.client.AbstractXhrTransport.executeInfoRequest(AbstractXhrTransport.java:155) ~[spring-websocket-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.web.socket.sockjs.client.SockJsClient.getServerInfo(SockJsClient.java:286) ~[spring-websocket-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.web.socket.sockjs.client.SockJsClient.doHandshake(SockJsClient.java:254) ~[spring-websocket-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.web.socket.messaging.WebSocketStompClient.connect(WebSocketStompClient.java:274) [spring-websocket-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.web.socket.messaging.WebSocketStompClient.connect(WebSocketStompClient.java:255) [spring-websocket-4.3.3.RELEASE.jar:4.3.3.RELEASE]
(...)
at java.lang.Thread.run(Thread.java:745) ~[na:1.8.0_74]
Caused by: java.net.ConnectException: Connection refused: connect
我如何才能对我的 Spring Boot 应用程序提供的 websocket 进行“自连接”的正确测试?
【问题讨论】:
-
如果您在测试中使用
@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)之类的东西,请确保您实际使用了正确的端口。日志中的错误消息表明您将端口硬编码到 URI 中(数字看起来像 ^^)。如果端口不正确,您将只获得您的堆栈跟踪。 Spring 提供了发现端口的方法,请参阅here。 -
接受的答案对您有用吗?我遇到了与您相同的错误,并且我正在关注已接受答案中提到的相同链接,您是否做了不同的事情?
标签: java spring junit websocket spring-websocket