title: How to unit test a class which uses HttpURLConnection internally?
body: <p>I'm looking for the best way to test a class which internally makes HTTP requests to a pre-defined URL. Generally, the class in question looks more or less like this :</p>
  
  <pre><code>public class ServiceAccess {
      private static final String SERVICE_URL = "http://someservice.com/";
      public ServiceAccess(String username) throws IOException, 
          UserNotFoundException, MalformedURLException {
          URL url = new URL(SERVICE_URL + username);
          HttpURLConnection conn = (HttpURLConnection)url.openConnection();
          if(conn.getResponseCode() == HTTP_NOT_FOUND) {
              throw new UserNotFoundException("user not found : " + username);
          }
          // and some more checks
      }
  }
  </code></pre>
  
  <p>I would like to test that the class properly reacts to the HTTP server's responses, including response codes, header fields, and such. I found the <a href="https://code.google.com/p/mockwebserver/" rel="nofollow">mockwebserver</a> library that looks just like something I need. However, in order to use it, I would need to somehow change the URL that the class connects to.</p>
  
  <p>The only sensible option that I see is to pass the URL in the constructor : however, it seems to me that this does not play too well in terms of design, since requiring the client to pass an URL to such a class looks fishy. Furthermore, I have not seen any other web service access libraries (<a href="http://twitter4j.org/" rel="nofollow">Twitter4J</a>, <a href="http://restfb.com/" rel="nofollow">RestFB</a>) that would require their clients to pass the URL in order to actually use them.</p>
  
  <p>I'm not a Java whiz, but I'd like to get it as right as possible. All answers welcome.</p>