Perl 单元测试示例

以下是一个简单的 Perl 测试脚本示例,它提供了一些结构,允许测试被测试的类/包中的其他方法。该脚本使用简单的 ok/not ok 文本生成标准输出,称为 TAP(Test Anything Protocol)。

通常, prove 命令运行脚本并总结测试结果。

#!/bin/env perl
# CPAN
use Modern::Perl;
use Carp;
use Test::More;
use Test::Exception;
use Const::Fast;

# Custom
BEGIN { use_ok('Local::MyPackage'); }

const my $PACKAGE_UNDER_TEST => 'Local::MyPackage';

# Example test of method 'file_type_build'
sub test_file_type_build {
    my %arg    = @_;
    my $label  = 'file_type_build';
    my $got_file_type;
    my $filename = '/etc/passwd';

    # Check the method call lives
    lives_ok(
        sub {
            $got_file_type = $PACKAGE_UNDER_TEST->file_type_build(
                filename => $filename
            );
        },
        "$label - lives"
    );

    # Check the result of the method call matches our expected result.
    like( $got_file_type, qr{ASCII[ ]text}ix, "$label - result" );
    return;
} ## end sub test_file_type_build

# More tests can be added here for method 'file_type_build', or other methods.

MAIN: {

   subtest 'file_type_build' => sub {
      test_file_type_build();
      # More tests of the method can be added here.
      done_testing();
   };

   # Tests of other methods can be added here, just like above.

   done_testing();
} ## end MAIN:

最佳实践

测试脚本应该只测试一个包/类,但是可以使用许多脚本来测试包/类。

进一步阅读