BluetoothSocketIoThread extends Thread { public synchronized void close(boolean closeStreams, boolean closeSocket) { Log.d(TAG, "close. " + ThreadUtils.currentThreadToString()); mIsShuttingDown = true; if (closeStreams) { if (mInputStream != null) { try { mInputStream.close(); Log.d(TAG, "mInputStream closed. " + ThreadUtils.currentThreadToString()); } catch (IOException e) { Log.w(TAG, "Failed to close the input stream: " + e.getMessage() + " (thread ID: " + getId() + ")"); } } if (mOutputStream != null) { try { mOutputStream.close(); Log.d(TAG, "mOutputStream closed. " + ThreadUtils.currentThreadToString()); } catch (IOException e) { Log.w(TAG, "Failed to close the output stream: " + e.getMessage() + " (thread ID: " + getId() + ")"); } } } if (closeSocket && mSocket != null) { try { mSocket.close(); Log.d(TAG, "mSocket closed. " + ThreadUtils.currentThreadToString()); } catch (IOException e) { Log.w(TAG, "Failed to close the socket: " + e.getMessage() + " (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 testClose() throws Exception { Field shuttingDownField = mBluetoothSocketIoThread.getClass().getDeclaredField("mIsShuttingDown"); shuttingDownField.setAccessible(true); mBluetoothSocketIoThread.close(true, true); verify(mMockInputStream, times(1)).close(); verify(mMockOutputStream, times(1)).close(); verify(mMockBluetoothSocket, times(1)).close(); assertThat("Should be set to true if closing", shuttingDownField.getBoolean(mBluetoothSocketIoThread), is(true)); reset(mMockInputStream); reset(mMockOutputStream); reset(mMockBluetoothSocket); mBluetoothSocketIoThread.close(false, true); verify(mMockOutputStream, never()).close(); verify(mMockInputStream, never()).close(); verify(mMockBluetoothSocket, times(1)).close(); assertThat("Should be set to true if closing", shuttingDownField.getBoolean(mBluetoothSocketIoThread), is(true)); reset(mMockInputStream); reset(mMockOutputStream); reset(mMockBluetoothSocket); mBluetoothSocketIoThread.close(true, false); verify(mMockOutputStream, times(1)).close(); verify(mMockInputStream, times(1)).close(); verify(mMockBluetoothSocket, never()).close(); assertThat("Should be set to true if closing", shuttingDownField.getBoolean(mBluetoothSocketIoThread), is(true)); }