複雑なデータ構造に対するテストをする - Test::Deep編

HashやArrayを含む複雑なデータ構造を比較しテストする事のできるモジュールがTest::Deepです。

例えば、Hashの構造を比較したい場合、以下のようにcmp_deeplyというメソッドで比較する事ができます。

use strict;
use warnings;
use Test::More qw(no_plan);
use Test::Deep;

my $got      = { title => 'Moose', body => 'cool' };
my $expected = { title => 'Moose', body => 'good' };
cmp_deeply( $got, $expected );

失敗時には、どのキーが異なっているのかが表示されるのでわかりやすいですね。

# Failed test at testdeep.t line 8.
# Compared $data->{"body"}
# got : 'cool'
# expect : 'good'
# Looks like you failed 1 test of 1.
testdeep...... Dubious, test returned 1 (wstat 256, 0x100)
Failed 1/1 subtests

Happy Testing!