Test::Simple モジュールを使って Perl のテストを書いてみる
use Test::Simple tests => 2; # テスト数の設定 (計画しているテスト数を記述) ok(1+1==2); # テスト No.1 (OK) ok(1+1==0); # テスト No.2 (NG)実行結果は以下のようになる。
>perl test-simple.pl 1..2 ok 1 not ok 2 # Failed test (test-simple.pl at line 4) # Looks like you failed 1 tests of 2.上記のテスト用 perl ソースで 1 行目の想定テスト数を実際のテスト数と異なる数にしておくと
use Test::Simple tests => 3; # テスト数の設定 (計画しているテスト数を記述) ok(1+1==2); # テスト No.1 (OK) ok(1+1==0); # テスト No.2 (NG)実行結果
>perl test-simple.pl 1..3 ok 1 not ok 2 # Failed test (test-simple.pl at line 4) # Looks like you planned 3 tests but only ran 2.計画していたテスト数と実施されたテスト数が異なると注意が出る
Test::More
Test::More モジュールを使用すると Test::Simple よりも幅広いテストができる
use Test::More tests => 7; # テスト数の設定
ok(1+1==2); # Test No.1 (OK)
ok(1+1==0); # Test No.2 (NG)
# 等差チェック (is)
is(1+1, 2); # Test No.3 (OK) (等しいか?)
# 正規表現チェック (like)
like("abcde", qr/^a/); # Test No.4 (OK) (正規表現にマッチしているか?)
like("abcde", qr/^b/); # Test No.5 (NG)
# 比較 (cmp_ok)
cmp_ok(1+1, '<', 3); # Test No.6 (OK)
cmp_ok(1+1, '=', 2); # Test No.7 (OK)
実行結果は以下のようになる
>perl test-more.pl 1..7 ok 1 not ok 2 # Failed test (test-more.pl at line 4) ok 3 ok 4 not ok 5 # Failed test (test-more.pl at line 11) # 'abcde' # doesn't match '(?-xism:^b)' ok 6 ok 7 # Looks like you failed 2 tests of 7.Test::Base
Test::Base モジュールはテストデータとテスト手段を分けて記述することができる
use Test::Base;
plan tests => 1 * blocks;
filters {
input => [qw/chomp/],
expected => [qw/chomp/],
};
run {
my $block = shift;
is(increment($block->input), $block->expected);
};
# テスト対象関数
sub increment {
my ($arg1) = @_;
my $ret;
$ret = $arg1 + 1;
return $ret;
}
__END__
# 以下がテスト対象と期待される結果を記述するブロック
=== test 1 (OK)
--- input
1
--- expected
2
=== test 2 (NG)
--- input
1
--- expected
0
実行結果は以下のようになる
> perl test-base.pl 1..2 ok 1 not ok 2 # Failed test (test-base.pl at line 12) # got: '2' # expected: '0' # Looks like you failed 1 tests of 2.
0 件のコメント:
コメントを投稿