BluetoothSocketIoThread extends Thread { @Override public void run() { Log.d(TAG, "Entering thread (ID: " + getId() + ")"); byte[] buffer = new byte[mBufferSizeInBytes]; int numberOfBytesRead = 0; while (!mIsShuttingDown) { try { numberOfBytesRead = mInputStream.read(buffer); } catch (IOException e) { if (!mIsShuttingDown) { Log.d(TAG, "Disconnected: " + e.getMessage()); mListener.onDisconnected(e.getMessage(), this); } break; } if (numberOfBytesRead > 0) { mListener.onBytesRead(buffer, numberOfBytesRead, this); } if (mExitThreadAfterRead) { break; } } Log.d(TAG, "Exiting thread (ID: " + getId() + ")"); } BluetoothSocketIoThread(BluetoothSocket socket, Listener listener); BluetoothSocket getSocket(); @Nullable PeerProperties getPeerProperties(); void setPeerProperties(PeerProperties peerProperties); void setExitThreadAfterRead(boolean exit); int getBufferSize(); void setBufferSize(int bufferSizeInBytes); @Override void run(); boolean write(byte[] bytes); synchronized void close(boolean closeStreams, boolean closeSocket);  }
@Test public void testRun() throws Exception { mBluetoothSocketIoThread.setBufferSize(1); mBluetoothSocketIoThread.setExitThreadAfterRead(true); when(mMockInputStream.read(any(byte[].class))).thenReturn(0); ExecutorService service = Executors.newSingleThreadExecutor(); service.execute(mBluetoothSocketIoThread); Thread.sleep(1000); verify(mMockListener, never()).onBytesRead(any(byte[].class), anyInt(), any(BluetoothSocketIoThread.class)); mBluetoothSocketIoThread.setBufferSize(1); mBluetoothSocketIoThread.setExitThreadAfterRead(true); when(mMockInputStream.read(any(byte[].class))).thenReturn(1); service.shutdown(); while (!service.awaitTermination(1L, TimeUnit.SECONDS)) { System.out.println("Not yet. Still waiting for termination"); } service = Executors.newSingleThreadExecutor(); service.execute(mBluetoothSocketIoThread); Thread.sleep(1000); verify(mMockListener, atLeastOnce()).onBytesRead(any(byte[].class), anyInt(), any(BluetoothSocketIoThread.class)); service.shutdown(); while (!service.awaitTermination(1L, TimeUnit.SECONDS)) { System.out.println("Not yet. Still waiting for termination"); } }