Search code examples
perltestingteardown

Execute Check in Perl Test if (and only if) test case succeeds


I am using Test::Unit::TestCase for unit-testing in perl. Is there any way to do some special assertion in the tear_down sub, if - and only if - the current test succeeds so far.

sub set_up {
  my ($O_self) = @_;

  # prepare test case
}

sub tear_down {
  my ($O_self) = @_;

  # how to check if test succeeds so far?
  if (...) {
    $O_self->assert_something_special_for_all_tests();
  }
}

sub test_any1 {
   # some test
}

sub test_any2 {
   # some other test
}

Of course I can do the special check at the end of each test, but it would be much nicer to do it inside the tear_down so that I cannot forget the special check.


Solution

  • Test::Unit::TestCase hasn't been updated in 8 years. It doesn't use the normal Test::Builder infrastructure so it cannot be combined with other test modules. Avoid it if possible. If you want to do xUnit style testing in Perl, consider using Test::Class instead.

    Because it is built using Test::Builder, you can access the underlying Test::Builder object and ask it for the state of the test.

    sub teardown : Test(teardown) {
        my $self = shift;
        my $tb = $self->builder;
    
        my $all_tests_passing = !grep !$_, $tb->summary;
        do_something_extra if $all_tests_passing;
    };