How do you test code that uses HttpURLConnection (legacy)?

Testing code that utilizes HttpURLConnection can be challenging, especially when it comes to handling network connections and responses. To effectively test your code, you can use mocking frameworks such as Mockito or PowerMock, which will allow you to simulate network requests without actually making them. Below is an example of how to test code using HttpURLConnection:

// Example code for sending a GET request using HttpURLConnection public String sendGetRequest(String url) throws IOException { URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // Set request method con.setRequestMethod("GET"); // Get response code int responseCode = con.getResponseCode(); InputStream responseStream = (responseCode == HttpURLConnection.HTTP_OK) ? con.getInputStream() : con.getErrorStream(); BufferedReader in = new BufferedReader(new InputStreamReader(responseStream)); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); return response.toString(); } // Test case with Mockito @Test public void testSendGetRequest() throws Exception { HttpURLConnection mockConnection = Mockito.mock(HttpURLConnection.class); InputStream mockInputStream = new ByteArrayInputStream("response".getBytes()); Mockito.when(mockConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); Mockito.when(mockConnection.getInputStream()).thenReturn(mockInputStream); URL mockUrl = Mockito.mock(URL.class); Mockito.when(mockUrl.openConnection()).thenReturn(mockConnection); // Replace with your method to set the URL String result = sendGetRequest("http://mockurl.com"); assertEquals("response", result); }

HttpURLConnection Java HTTP Test Mockito Mocking Frameworks Java Unit Testing