websocket - 如何对 Spring WebSocketStompClient 进行单元测试
问题描述
我有一个 Stompclient,它连接到 Spring 引导服务器并执行一些订阅。此 websocket 客户端的代码覆盖率为 0%。我只能找到有关如何对 Spring Boot Websocket 服务器进行单元测试的代码示例。但这是客户端验证 Stompclient 工作正常。如果我的问题缺少任何细节,请告诉我。
这是我需要为其编写单元测试用例的示例连接方法。
StompSession connect(String connectionUrl) throws Exception {
WebSocketClient transport = new StandardWebSocketClient();
WebSocketStompClient stompClient = new WebSocketStompClient(transport);
stompClient.setMessageConverter(new StringMessageConverter());
ListenableFuture<StompSession> stompSession = stompClient.connect(connectionUrl, new WebSocketHttpHeaders(), new MyHandler());
return stompSession.get();
}
注意:客户端是轻量级 SDK 的一部分,因此它不会对该单元测试有重度依赖。
解决方案
感谢 Artem 的建议,我研究了 Spring websocket 测试示例。这是我为我解决的方法,希望这对某人有所帮助。
public class WebSocketStompClientTests {
private static final Logger LOG = LoggerFactory.getLogger(WebSocketStompClientTests.class);
@Rule
public final TestName testName = new TestName();
@Rule
public ErrorCollector collector = new ErrorCollector();
private WebSocketTestServer server;
private AnnotationConfigWebApplicationContext wac;
@Before
public void setUp() throws Exception {
LOG.debug("Setting up before '" + this.testName.getMethodName() + "'");
this.wac = new AnnotationConfigWebApplicationContext();
this.wac.register(TestConfig.class);
this.wac.refresh();
this.server = new TomcatWebSocketTestServer();
this.server.setup();
this.server.deployConfig(this.wac);
this.server.start();
}
@After
public void tearDown() throws Exception {
try {
this.server.undeployConfig();
}
catch (Throwable t) {
LOG.error("Failed to undeploy application config", t);
}
try {
this.server.stop();
}
catch (Throwable t) {
LOG.error("Failed to stop server", t);
}
try {
this.wac.close();
}
catch (Throwable t) {
LOG.error("Failed to close WebApplicationContext", t);
}
}
@Configuration
static class TestConfig extends WebSocketMessageBrokerConfigurationSupport {
@Override
protected void registerStompEndpoints(StompEndpointRegistry registry) {
// Can't rely on classpath detection
RequestUpgradeStrategy upgradeStrategy = new TomcatRequestUpgradeStrategy();
registry.addEndpoint("/app")
.setHandshakeHandler(new DefaultHandshakeHandler(upgradeStrategy))
.setAllowedOrigins("*")
.withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry configurer) {
configurer.setApplicationDestinationPrefixes("/publish");
configurer.enableSimpleBroker("/topic", "/queue");
}
}
@Test
public void testConnect() {
TestStompClient stompClient = TestStompClient.connect();
assert(true);
}
}
推荐阅读
- asp.net - 两个不同 Web 应用程序上的 ASP.Net Identity PasswordHash 问题
- scala - 如何在流式查询中执行动态 SQL?
- php - 如何从现在开始在 PHP 中获得时差估计。类似于 moment.js fromNow() 函数
- java - 避免 ORA-00904 - 在 java 中执行 sql 查询时出现无效标识符错误,因为该列可能会或可能不会在数据库中预设
- android - 只能在草稿应用上创建状态为草稿的版本
- java - 在哪里可以找到已安装的 javadoc
- python - 如何在 Seaborn 中更改轴的字体大小?
- python - 如何更新我的 Mac 以使用最新版本的 Python?
- bitbar - 在 BitBar 上共享文件
- javascript - 如何在烧瓶应用程序中显示particles.js 库?