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:

最佳實踐

測試指令碼應該只測試一個包/類,但是可以使用許多指令碼來測試包/類。

進一步閱讀