arc_of_descent has asked for the wisdom of the Perl Monks concerning the following question:

Greetings,

I recently got my hands dirty with Test::MockModule, and was successfully able to use it. I was just wondering if I'm heading in the right direction though, and would appreciate any comments and suggestions.

I have an object, say $obj, and I want to test its login and get_info methods. $obj uses LWP::UserAgent and both the mentioned methods make an HTTP request and expect some reponse.

For the sake of simplicity, assume these methods just return the HTTP response code. In the practice of good testing, I'm not relying on an active internet connection, and thus I decided to fake the LWP::UserAgent's request method in my test script.

This is how the test script looks like:

use Test::More tests => 2; use Test::MockModule; my $obj = MyModule->new(); # Test the login method { my $lwp = Test::MockModule->new( 'LWP::UserAgent' ); $lwp->mock( request => sub { # Return a hand crafted HTTP::Response object my $response = HTTP::Response->new; $response->code(200); $response->content('Login Successfull'); return $response; }); my $code = $obj->login(); ok($code == 200, 'login'); } # Test the get_info method { my $lwp = Test::MockModule->new( 'LWP::UserAgent' ); $lwp->mock( request => sub { # Return a hand crafted HTTP::Response object my $response = HTTP::Response->new; $response->code(302); $response->content('Some Info'); return $response; }); my $code = $obj->get_info(); ok($code == 302, 'get_info'); }

Essentially, every method of $obj involves a HTTP request, and in my test script I am mocking LWP::UserAgent's request method and returning some pre-determined data through a hand crafted HTTP::Response object.

What I need advice on is:

Thanks for reading.


--
Rohan

Replies are listed 'Best First'.
Re: How to use Test::MockModule better
by dragonchild (Archbishop) on Jan 11, 2006 at 14:29 UTC
    First off, Test::Builder won't help because it's used to build the testing infrastructure, not specific tests.

    As for what you're looking for, I can't tell you how to solve it. But, I can tell you how we solved it in DBD::Mock for database work. We used what we call sessions - sequences of expected SQL statements, their expected bind parameters, and what they should be returning. We set one up, then call the code under test. Either the session passes or it doesn't.

    It sounds like you really want to set up a session of HTTP requests with the responses lined up in a row so you can test a specific scenario.


    My criteria for good software:
    1. Does it work?
    2. Can someone else come in, make a change, and be reasonably certain no bugs were introduced?