Skip navigation.

Perl Unit Testing... and there's Test::More... optional set_up & tear_down

unit testing

It's funny... people ask me why I like testing... This is an excellent example... small, digestible but makes the point...

I often find it more challenging to test something rather than make something...

Remember my first post on Perl Unit Testing ?

Well, I was getting fed up of being forced to have a set_up and tear_down in every test - whether I needed them both or not!

So... the code to make this possible is easy...


        &main::set_up if main->can('set_up');
	&$block;
	&main::tear_down if main->can('tear_down');


Although one experienced perl developer told me that '->can' only worked against packages :-P

But how do you make sure that both are optional?

Basically, you have to make sure that they don't exist and then when you want them, make them magically appear.

Enter... Sub::Install

I haven't got time to explain it all... but have a read of this and see if you can work it out... should be simple enough...

For such a small amount of code, even the most basic of tests (as I am doing here) are usually more interesting than the application code you are testing...

Enjoy...

The test


use strict;
use lib '..';
use Test::More::LikeXUnit 'no_plan';
use Test::Exception;
use Sub::Install;

use constant TRUE 	=> 1;
use constant FALSE 	=> 0;

my $is_setup = FALSE;

BEGIN {
    test 'should not mind if set_up or tear_down exists' , sub {
        is ($is_setup , undef , 'Should not be setup');
    };
}

Sub::Install::install_sub ({
    code => sub { $is_setup = TRUE;},
    into => 'main',
    as   => 'set_up'
});

Sub::Install::install_sub ({
    code => sub { $is_setup = FALSE;},
    into => 'main',
    as   => 'tear_down'
});

test 'setup test', sub {
	ok( $is_setup, 'should have been setup' );
};

is( $is_setup, FALSE , 'Should have been torn down');

test ( 'Should be able to do more than one test', sub {
	ok( $is_setup, 'should have been setup' );
});

is( $is_setup, FALSE , 'Should have been torn down');


The package


package Test::More::LikeXUnit;

use strict;
use warnings;

use base 'Test::More';
use Test::More;
@Test::More::LikeXUnit::EXPORT = ( @Test::More::EXPORT, 'test' );

use constant LOG_COMMENT_CHARACTER => '#';

sub test {
	my $description = shift;
	my $block = shift;
	print "\n" . LOG_COMMENT_CHARACTER ."-----" . $description . "\n";
	&main::set_up if main->can('set_up');
	&$block;
	&main::tear_down if main->can('tear_down');
}


1;

I still miss my Java or .NET standard of IDE, refactoring and productivity tools... but in a world of 'vim' and a 'nix command line, little things like this make working with Perl even more fun.

CPAN Release?

That looks handy, we were just talking about better separation of units on perl-qa. Where's the CPAN release?

Comment viewing options

Select your preferred way to display the comments and click 'Save settings' to activate your changes.