如何对Spring WebSocketStompClient进行单元测试

时间:2018-08-07 19:41:12

标签: websocket spring-websocket

我有一个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的一部分,因此该单元测试不能具有严重的依赖性。

1 个答案:

答案 0 :(得分:0)

感谢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);
}
}