Skip navigation.

Perl Unit testing... Test::More and Test::Group

unit testing

In a previous post on Perl Unit Testing I illustrated one way of improving the readability of Test::More tests.

Subsequently, I remembered that Perl allows you to remove clutter by selectively not using parenthesis. This makes the tests read even more cleanly if omitted from the frist and last lines:


        test 'foo can't be demoralised' , sub {
		$foo->set_bar( HIGH );
		
		throws_ok ( sub { 
			$foo->set_bar( LOW ); 
		} , 
		qr/Should not let others lower the bar/ ,
		'Should not allow lowering of bar');
		
		ok( $foo->is_high_achiever , 
                    'Should still be a high achiever' );
	};


All I have done is remove two parenthesis but it makes the code much easier on the eye... IMHO

Rija Menage then found two very similar CPAN modules:...

(I had looked but obviously not hard enough).

Test::Class supports setup and teardown but I found the syntax reasonably readable but a little fiddly. It uses a subroutine attribute (hence the colon before the "Test" keyword below):


 sub test_push : Test {
     $foo->set_bar( HIGH );
		
		throws_ok ( sub { 
			$foo->set_bar( LOW ); 
		} , 
		qr/Should not let others lower the bar/ ,
		'Should not allow lowering of bar');
		
		ok( $foo->is_high_achiever , 'Should still be a high achiever' );
  };

Test::Group allows you to write in the same style as Test::More::LikeXUnit (see first example above). Unfortunately it doesn't seem to provide automatic setUp and tearDown features.

It also has another neat feature:

...test output is much shorter and more readable: only failed subtests show a diagnostic, while test groups with no problems inside produce a single friendly ok line;

I like!

I need to do a little more to make sure that set_up and tear_down are optional. At the moment, they need to be in the ".t" (test) file, even if they are empty. Once I've done that, I'll refactor so that my module extends Test::Group then contact the original author to see if they will add the feature.