@Before public void setUp() throws IOException { HttpUrl url = mock(HttpUrl.class); client = new HttpClient(url); connection = mock(HttpURLConnection.class); when(url.openConnection()).thenReturn(connection); }
@Test public void post_shouldPostUrlParametersAndGetResponse() throws IOException { Map<String, String> parameters = new TreeMap<>(); parameters.put("one", "one"); parameters.put("two", "two"); ByteArrayOutputStream stream = new ByteArrayOutputStream(); when(connection.getOutputStream()).thenReturn(stream); when(connection.getInputStream()).thenReturn(new ByteArrayInputStream("response".getBytes())); String response = client.post(parameters); verify(connection).setDoOutput(true); verify(connection).setDoInput(true); verify(connection).setRequestMethod("POST"); verify(connection).setRequestProperty("Content-Length", String.valueOf(16)); verify(connection).setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); assertThat(stream.toString(), is("&one=one&two=two")); assertThat(response, CoreMatchers.containsString("response")); } }
data.put("passphrase", passphrase); String response = implementationIdHttpClient.post(data); response = response.trim();