in reply to Do you use loops in your unit tests?
I use this style of testing quite often. (C.f. Re^2: Wanted, more simple tutorials on testing) While it's not the most elegant, I find it quick to get started this way before I've really decided how the tests will evolve and what the common setup/teardown will be and then it's relatively easy to extend and refactor as needed.
I often put one or more *.pm files in the "t" directory with either helper functions or to to encapsulate repetitive tests. This is where Test::More with Test::Builder and $Test::Builder::Level are quite helpful. Essentially, you can create custom test modules on the fly as needed to refactor cut-and-paste tests from multiple parts of your *.t files.
# foo.t use strict; use warnings; use Test::More; # don't put a plan here use t::Helper qw/multi_test/; # i.e. t/Helper.pm my @cases = ( { label => "describe this case", input => "data to operate on", output => "expected result", }, # ... repeat as needed ... ); # set plan after populating @cases my $tests_per_case = 2; plan tests => 1 + $tests_per_case * @cases; # start testing here require_ok( "Some::Object" ); for my $case ( @cases ) { my $obj = Some::Object->new; multi_test( $obj, $case ); }
# t/Helper.pm use strict; use warnings; use base 'Exporter'; our @EXPORT = qw/multi_test/; sub multi_test { my ($obj, $case) = @_; local $Test::Builder::Level = $Test::Builder::Level + 1; is( $obj->wibble( $case->{input} ), $case->{output}, "wibble: $case->{label}" ); ok( $obj->wobble, "wobble: $case->{label} ); } 1;
You can see a range of examples in the *.t files in some of my CPAN modules:
Statistics::RankOrder -- this one uses a HoH instead of an AoH to hold test data but is otherwise similar.
Pod::WikiDoc -- here I use a t::Casefiles helper object to pull data from files and iterate over it. (C.f. RFC: Test::Cases -- Worth releasing?)
CPAN::Reporter -- an example that has grown to the point where more aggressive refactoring is pretty desperately needed.
-xdg
Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.
|
|---|