Best practice for unit tests that rely on internet access?

Avleen Vig avleen at
Fri Apr 29 03:38:04 BST 2011

On Thu, Apr 28, 2011 at 8:15 PM, Toby Wintermute <tjc at> wrote:

> What is the best practice for writing unit tests that rely on internet
> access?
> ie. You have a CPAN module which is all about talking to a web
> service.. So you have unit tests that do just that.
> What if the system testing it doesn't allow HTTP connections out? The
> tests will fail..
> Should one
> a) Prompt the user for whether to skip the tests? (I hate this
> option.. I dislike interactivity in installers)
> b) Only run the tests if specifically set by AUTHOR_TEST or something,
> otherwise mock the server? (I dislike this.. means few good tests run
> for users)
> c) Try to test if there's a working connection, and silently skip the
> tests if not? (Risks skipping tests if the connect fails for other
> reasons than no outbound HTTP allowed)
> d) ???

Mock the connection locally.
Open a socket on a random local port, connect to it, and make sure your code
handles data it should sent/receive correctly, then close the socket.

Unit tests shouldn't (imo) connect to some external service outside the
local scope.
One you test the successful connection, you should then test how your code
handles an unsuccessful connection by connecting to a local port which is

Finally, have your app connect to another open port which just hangs and
doesn't do anything, and make sure your app times out correctly.

More information about the mailing list