春季启动时的Websocket客户端单元测试

时间:2019-06-26 09:54:47

标签: spring-boot junit websocket spring-websocket java-websocket

我有一个带有websocket客户端代码的spring boot项目,我想为此编写junit test。但是我不确定如何在单元测试中模拟websocket行为。如何编写junit测试?

@ClientEndpoint
public class WebSocketClient {

    private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketClient.class);
    private Session userSession = null;
    private MessageHandler messageHandler;

    public WebSocketClient(URI endpoint) {
        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        container.setDefaultMaxTextMessageBufferSize(1024 * 1024);
        container.setDefaultMaxBinaryMessageBufferSize(1024 * 1024);
        try {
            container.connectToServer(this, endpoint);
        } catch (Exception e) {
            LOGGER.error(String.format("Exception occurred when connecting to websocket server %s", e.getMessage()));
        }
    }

    @OnOpen
    public void onOpen(Session userSession) {
        this.userSession = userSession;
    }

    @OnClose
    public void onClose(Session userSession, CloseReason reason) {
        this.userSession = null;
    }

    @OnMessage
    public void onMessage(String message) {
        if (this.messageHandler != null) {
            this.messageHandler.handleMessage(message);
        }
    }

    public void addMessageHandler(MessageHandler msgHandler) {
        this.messageHandler = msgHandler;
    }

    public static interface MessageHandler {
        void handleMessage(String message);
    }
}

我希望至少看到用于连接服务器和消息方法的单元测试。

0 个答案:

没有答案