What's Test::Class Doing?

So much of software engineering is about complexity management. You find common patterns and abstract them out. You tease apart complex inheritance hierarchies. You decouple unrelated behaviours and find different pieces are simpler as a result.

In the process of this, you might be using Test::Class for your test suite. It's a fantastic module, but even people who've been using it for years can sometimes be surprised by its behaviour. One nifty way of understanding what's going on is to have your common base class tell you more. Here's one simple trick which might surprise you.

package My::Test::Class;

use Test::Class::Most;

INIT {
  Test::Class->runtests;
}

sub startup : Tests(startup) {
  my $self  = shift;
  my $class = ref $self;
  explain "Running startup for $class";
}

sub setup : Tests(setup) {
  my $self  = shift;
  my $class = ref $self;
  explain "Running setup for $class";
}

sub teardown : Tests(teardown) {
  my $self  = shift;
  my $class = ref $self;
  explain "Running teardown for $class";
}

sub shutdown : Test(shutdown) {
  my $self  = shift;
  my $class = ref $self;
  explain "Running shutdown for $class";
}

1;

This assumes you've used the best practices outlined in my Test::Class tutorial. Specifically, many people have methods like zz_shutdown to rely on the alphabetical ordering of how test control methods fire. Don't do that. These are objects. Override them properly:

sub shutdown : Tests(shutdown) {
    my $test = shift;
    # do all of your shutdown stuff
    $test->next::method;
}

By properly overriding these methods, you gain full control over the order the parent methods fire (if they fire at all), and with that base class above, you can get an interesting trace of which test control methods fire. I found out, for example, that one of the test control methods had failed to call the parent method, thus explaining why some fixture data was missing.

This is a useful enough technique that I might just push it directly in Test::Class, assuming I can find a clean interface.

Leave a comment

About Ovid

user-pic Have Perl; Will Travel. Freelance Perl/Testing/Agile consultant. Photo by http://www.circle23.com/. Warning: that site is not safe for work. The photographer is a good friend of mine, though, and it's appropriate to credit his work.