concept HttpURLConnection in category java

appears as: HttpURLConnection
JUnit in Action MEAP V06

This is an excerpt from Manning's book JUnit in Action MEAP V06.

  • We start by opening an HTTP connection using the HttpURLConnection class (#A).
  • JUnit in Action, Second Edition

    This is an excerpt from Manning's book JUnit in Action, Second Edition.

    We start by opening an HTTP connection using the HttpURLConnection class. We then read the stream content until there’s nothing more to read . If an error occurs, we return null . One might argue that a better implementation should throw an exception. But for testing purposes, returning null is fine.

    The last step is to create a stub implementation of the HttpURLConnection class so you can return any value you want for the test. Listing 6.7 shows a simple implementation that returns the string "It works" as a stream to the caller.

    Listing 6.7. Stubbed HttpURLConnection class

    HttpURLConnection is an abstract public class that doesn’t implement an interface, so you extend it and override the methods wanted by the stub. In this stub, you provide an implementation for the getInputStream method because it’s the only method used by your code under test. Should the code to test use more APIs from HttpURLConnection, you’d need to stub these additional methods. This is where the code would become more complex—you’d need to reproduce completely the same behavior as the real HttpURLConnection. For example, at , you test that if setDoInput(false) has been called in the code under test, then a call to the getInputStream method returns a ProtocolException. (This is the behavior of HttpURLConnection.) Fortunately, in most cases, you need to stub only a few methods and not the whole API.

    sitemap

    Unable to load book!

    The book could not be loaded.

    (try again in a couple of minutes)

    manning.com homepage
    test yourself with a liveTest