Testing networking client code using Test::LWP::UserAgent
Test::LWP::UserAgent is a module I wrote after writing several networking client libraries for
$work with inconsistent and spotty test coverage — what I most wanted to do was fully simulate the server end of a network connection, without having to delve deeply into LWP's internal implementation, nor mock a lot of methods, which the traditional mock object approach would require.
Exploring the options available led me to Yury Zavarin's Test::Mock::LWP::Dispatch, whose API I adapted into the initial version of Test::LWP::UserAgent. It behaves exactly like LWP::UserAgent, one of the most popular HTTP client libraries in perl, in all respects except for the portion that actually sends the request out to the network - at that point it returns the first response that you have preconfigured that matches the outbound request.
In the above example, no outbound reqest passing through this user agent will use the live network (this is the default behaviour). Any request whose URI matches
/example.com/ will receive an HTTP 200 response, and the remaining requests will return a 404.
If, however, you wish to capture only some requests, while letting the remainder use the network normally, you can enable the
And indeed if you inspect the
$response object returned, you will see that it contains the actual network response from contacting http://google.com.
Configuration can also be done globally, if you want all user agents in your program to use the same settings (or if you do not have direct control over the actual user agent object being used, but just its class):
Test::LWP::UserAgent inherits from LWP::UserAgent, so it satisfies
isa requirements that you may have via Moose or another system that uses type checking. This means that all the normal options available in LWP::UserAgent are still available to you, and work identically, for example:
You can also use Test::LWP::UserAgent to connect to a local PSGI application seamlessly, which can be very useful when you have a client and server installed on the same box but do not want to fuss with separate code for handling this case, or if you want more fine-grained control over what responses to send:
The code examples above are fleshed out as fully-working code in the examples/ directory under http://metacpan.org/release/Test-LWP-UserAgent, along with a detailed example of some unit tests for a hypothetical networking client library.