Advanced Testing!

Test::Moreのis(), ok()だけで終わらせていたらもったいない!
ってことでいろいろ使ってみる。

Test::Moreをもう一歩踏み込んで使う
  • is_deeply
    • 構造レベルまでチェックしたい時に使う。
my $ref_hash;
$ref_hash->{key} = 'val';
is_deeply($ref_hash, {key => 'val'}, 'deeply same');
  • diag
    • テスト失敗時に強制的にメッセージ出力するのに使う。
ok(0) or diag('0 is false');
  • note
    • proveを-vオプション付で実行した時に出力。
    • 細かいDebugメッセージを出力するならコレ。
ok(1);
note('note will be printed when you enter "prove -v"');
  • explain
    • human readableに出力
note({ key => 'val'});          # orz cannot read..
note(explain({ key => 'val'})); # good!!!
  • $Test::Builder::Level
    • サブルーチン化されたテストは失敗時のトレースが難しい
    • 例えば以下のコードでは『at UnitTest/t/02-Test-Builder-Level.t line 4.』と出力されてしまう
use Test::More qw(no_plan);

sub num {
    is($_[0], 0, 'test');
}

num(1);
    • こういうケースでは$Test::Builder::Levelをlocalで+1するとよい
use Test::More qw(no_plan);

sub num {
    local $Test::Builder::Level = $Test::Builder::Level + 1;
    is($_[0], 0, 'test');
}

num(1);
Test::Exception
    • 例外をテストするためのモジュール
use Test::More qw(no_plan);
use Test::Exception;

sub am_i_die {
    my $arg = shift;
    if ($arg) {
        die;
    }
}
sub throw_object {
    my $obj = bless({}, 'Exception');
    die $obj;
}

lives_ok { am_i_die(0); };
dies_ok  { am_i_die(1); };
throws_ok{ throw_object; } 'Exception';
Devel::Cover
    • テストカバレッジを調べるモジュール
    • 付属のcoverコマンドを使う
cover -test
Test::Base

A Data Driven Testing Framework。テストデータとテストコードを分離できるので、便利。

  • 複数パラメタを指定
    • 最初、わからなくてハマった
run {
   my $block = shift;
   my @input = $block->input;

   is($input[0], 'd', 'ok');
   is($input[1], 1, 'ok');
};

done_testing();

__END__

=== test1
--- input chomp lines chomp
d
1

=== test2
--- input eval: qw(d 1)