[pm-h] Test::Group example

G. Wade Johnson gwadej at anomaly.org
Wed Aug 6 18:19:15 PDT 2008


To give an idea of one way to use Test::Group, here's an example from a
module I just "finished". It would be used like this

quantity_ok( $q, 'a quantity',
      { value => 3.14, units => 'lb', str => '3.14 lb' }
);

Despite the fact that it does 5 sub-tests, it would still count as one
test.

See the code below:
-------------------------------------------
#
# Special test method that allows for specialized testing of Quantity
# objects. The arguments to this function are
#
# $q - Quantity object to test
# $name - name of the test
# $desc - description of the tests to run as a hashref
#
# The $desc hashref contains tells which individual subtests to run on
# the object. The defined subtests are:
#
# null - if set to the true value test is_null() returns true, defaults
#        to testing if it is false.
# value - the result of the value() method must match the value of this
#         parameter
# units - the result of the units() method must match the value of this
#	  parameter
# str - the results of stringify() direct interpolation of the object
#       must match the value of this parameter.
#
# In addition, the object is always tested if it is a Quantity
#
sub quantity_ok
{
    my $q = shift;
    my $name = shift;
    my $desc = shift;

    test $name => sub {
        isa_ok( $q, 'Weather::Bug::Quantity' );
        if( $desc->{null} )
        {
            ok( $q->is_null(), "is null Quantity" );
        }
        else
        {
            ok( !$q->is_null(), "is not null Quantity" );
        }
        if( exists $desc->{value} )
        {
            is( $q->value(), $desc->{value}, "value matches" );
        }
        if( exists $desc->{units} )
        {
            is( $q->units(), $desc->{units}, "units match" );
        }
        if( exists $desc->{str} )
        {
            is( $q->stringify(), $desc->{str}, "string form correct" );
            is( "$q", $desc->{str}, "string form correct, overload" );
        }
    };
}
---------------------------------------------

This is not a solution to all problems, but it does help clean up a
class of them I've been annoyed by.

G. Wade
-- 
As a software development model, Anarchy does not scale well.
                                                       -- Dave Welch


More information about the Houston mailing list