【问题标题】:How to unit test Spring WebSocketStompClient如何对 Spring WebSocketStompClient 进行单元测试
【发布时间】:2018-08-07 19:41:12
【问题描述】:
我有一个 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 的一部分,因此它不会对该单元测试有严重依赖。
【问题讨论】:
标签:
websocket
spring-websocket
【解决方案1】:
感谢 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);
}
}