### Question:
WebSocket extends Transport { @Override public void send(List<Packet<?>> packets) { final Parser.EncodeCallback<?> encodeCallback = data -> { try { if(data instanceof String) { mConnection.write((String) data); } else if(data instanceof byte[]) { mConnection.write((byte[]) data); } } catch (IOException ex) { onError("write error", ex.getMessage()); } }; for (Packet<?> packet : packets) { ServerParser.encodePacket(packet, true, encodeCallback); } } WebSocket(EngineIoWebSocket webSocket); @Override void onRequest(HttpServletRequest request, HttpServletResponse response); @Override void send(List<Packet<?>> packets); @Override boolean isWritable(); @Override String getName(); static final String NAME; }### Answer:
@Test public void testSend_string() { final EngineIoWebSocket webSocketConnection = Mockito.mock(EngineIoWebSocket.class); final WebSocket webSocket = Mockito.spy(new WebSocket(webSocketConnection)); final String stringData = "Test string"; final Packet<?> packet = new Packet<>(Packet.MESSAGE, stringData); webSocket.send(new ArrayList<Packet<?>>() {{ add(packet); }}); Mockito.verify(webSocket, Mockito.times(1)).send(Mockito.anyList()); ServerParser.encodePacket(packet, true, data -> { try { Mockito.verify(webSocketConnection, Mockito.times(1)) .write(Mockito.eq((String) data)); } catch (IOException ignore) { } }); }
@Test public void testSend_binary() { final EngineIoWebSocket webSocketConnection = Mockito.mock(EngineIoWebSocket.class); final WebSocket webSocket = Mockito.spy(new WebSocket(webSocketConnection)); final byte[] binaryData = "Test string".getBytes(StandardCharsets.UTF_8); final Packet<?> packet = new Packet<>(Packet.MESSAGE, binaryData); webSocket.send(new ArrayList<Packet<?>>() {{ add(packet); }}); Mockito.verify(webSocket, Mockito.times(1)).send(Mockito.anyList()); ServerParser.encodePacket(packet, true, data -> { try { Mockito.verify(webSocketConnection, Mockito.times(1)) .write(Mockito.eq((byte[]) data)); } catch (IOException ignore) { } }); }
@Test public void testSend_error() throws IOException { final EngineIoWebSocket webSocketConnection = Mockito.mock(EngineIoWebSocket.class); final WebSocket webSocket = Mockito.spy(new WebSocket(webSocketConnection)); Mockito.doThrow(new IOException()).when(webSocketConnection).write(Mockito.anyString()); webSocket.on("error", args -> { }); final String stringData = "Test string"; final Packet<?> packet = new Packet<>(Packet.MESSAGE, stringData); webSocket.send(new ArrayList<Packet<?>>() {{ add(packet); }}); Mockito.verify(webSocket, Mockito.times(1)) .send(Mockito.anyList()); Mockito.verify(webSocket, Mockito.times(1)) .emit(Mockito.eq("error"), Mockito.eq("write error"), Mockito.isNull()); }