HttpClient implements RemoteService { public Response post(final String data, final String url) throws IOException { Response response = new Response(); HttpURLConnection connection = null; DataOutputStream out = null; InputStream in = null; try { connection = createConnection(url); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); out = new DataOutputStream(connection.getOutputStream()); out.write(data.getBytes("UTF-8")); out.flush(); out.close(); out = null; in = connection.getInputStream(); response.body = new String(Utils.getBytes(in), Charset.forName("UTF-8")); response.code = connection.getResponseCode(); in.close(); in = null; } catch (final IOException e) { if (connection != null && (response.code = connection.getResponseCode()) >= HTTP_BAD_REQUEST) { Logger.log(TAG, "Failed post to IB. StatusCode: " + response.code, Logger.SDK_DEBUG); } else { throw e; } } finally { if (null != connection) connection.disconnect(); if (null != out) out.close(); if (null != in) in.close(); } return response; }  static HttpClient getInstance(); Response post(final String data, final String url);  }
@Test public void postTest() throws Exception { DataOutputStream outMock = mock(DataOutputStream.class); InputStream inMock = mock(InputStream.class); when(mMockConn.getOutputStream()).thenReturn(outMock); when(mMockConn.getInputStream()).thenReturn(inMock); when(inMock.read(any(byte[].class), anyInt(), anyInt())).thenReturn(-1); when(mMockConn.getResponseCode()).thenReturn(200); assertEquals(mClient.post("foo", "localhost").code, 200); when(mMockConn.getResponseCode()).thenReturn(500); assertEquals(mClient.post("bar", "localhost").code, 500); when(mMockConn.getResponseCode()).thenReturn(501); when(mMockConn.getInputStream()).thenThrow(new IOException()); assertEquals(mClient.post("bar", "localhost").code, 501); verify(mMockConn, times(3)).setRequestMethod("POST"); verify(mMockConn, times(3)).disconnect(); verify(outMock, times(3)).close(); verify(inMock, times(2)).close(); }