如何正确模拟WebSocket会话?

时间:2018-04-15 20:46:59

标签: java unit-testing spring-boot junit mockito

我使用springBoot创建了一个简单的websocket应用程序。我是Mockito的新手,我正在尝试使用mockito和junit对下一课的行为进行单元测试。

@Component
public class TextHandler extends TextWebSocketHandler {

WebSocketSession session;

@Override
public void handleTextMessage(WebSocketSession session, TextMessage message)
        throws InterruptedException, IOException {

        // send message
        if (session.isOpen()) {
            try {

                session.sendMessage(new TextMessage("Hello from the websocket"));
            } finally {
                session.close();
            }
        } else {
            System.out.println("no open session available");
        }
}

我为测试包下的会话创建了一个存根,如下所示。

@Component
public class WebSocketSessionStub implements WebSocketSession{

@Override
public String getId() {

    return "SESSION1";
}

@Override
public URI getUri() {
    // TODO Auto-generated method stub
    return null;
}

@Override
public HttpHeaders getHandshakeHeaders() {
    // TODO Auto-generated method stub
    return null;
}

@Override
public Map<String, Object> getAttributes() {
    // TODO Auto-generated method stub
    return null;
}

@Override
public Principal getPrincipal() {
    // TODO Auto-generated method stub
    return null;
}

@Override
public InetSocketAddress getLocalAddress() {
    // TODO Auto-generated method stub
    return null;
}

@Override
public InetSocketAddress getRemoteAddress() {
    // TODO Auto-generated method stub
    return null;
}

@Override
public String getAcceptedProtocol() {
    // TODO Auto-generated method stub
    return null;
}

@Override
public void setTextMessageSizeLimit(int messageSizeLimit) {
    // TODO Auto-generated method stub

}

@Override
public int getTextMessageSizeLimit() {
    // TODO Auto-generated method stub
    return 0;
}

@Override
public void setBinaryMessageSizeLimit(int messageSizeLimit) {
    // TODO Auto-generated method stub

}

@Override
public int getBinaryMessageSizeLimit() {
    // TODO Auto-generated method stub
    return 0;
}

@Override
public List<WebSocketExtension> getExtensions() {
    // TODO Auto-generated method stub
    return null;
}

@Override
public void sendMessage(WebSocketMessage<?> message) throws IOException {
    // TODO Auto-generated method stub

}

@Override
public boolean isOpen() {
    System.out.println("isOpen");
    return true;
}

@Override
public void close() throws IOException {
    // TODO Auto-generated method stub

}

@Override
public void close(CloseStatus status) throws IOException {
    // TODO Auto-generated method stub

   }

 }

以下是我的单元测试课程。

@RunWith(SpringRunner.class)
@SpringBootTest
public class TextHandlerTest {

@Autowired
TextHandler textHandler;

@Mock
WebSocketSessionStub ws;

@Mock
WebSocketMessage<TextMessage> webSocketMessage;

TextMessage textMsg = new TextMessage("Test Message".getBytes());

@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
    textHandler.handleMessage(ws, textMsg);     
}


@Test
public void verifyCallToIsOpenConnection() throws Exception {

    verify(ws, times(1)).isOpen();
    System.out.println("isOpen " + ws.isOpen());

 }

}

以上测试通过,但isOpen评估为false。因此,我无法验证sendMessage方法调用。我怎样才能纠正它?

1 个答案:

答案 0 :(得分:3)

您可以模拟WebSocketSession并将其注入TextHandler#handleTextMessage

/*  
 *  You don't need spring context while mocking. 
 *  Hence No need to have spring runner. 
 */
@RunWith(MockitoJunitRunner.class)
public class TextHandlerTest {

    @Test
    public void verifyCallToIsOpenConnection() {
         WebSocketSession session = mock(WebSocketSession.class);
         TextMessage textMsg = new TextMessage("Test Message".getBytes());

         when(session.isOpen()).thenReturn(true);

         TextHandler textHandler = new TextHandler();

         // Pass the mocked session object here
         textHandler. handleTextMessage(session, textMsg);

         // Now you can verify if session.sendMessage() was called or not
         verify(session, times(1)).sendMessage(textMsg);
    }
}