Perl-Test-系列模块

主要查看 perldoc Test::Tutorial 文档.

在使用 ok() 等函数时, 需要注意提供足够的描述信息来 debug.

Test::Simple 模块

其仅提供一个函数 ok(), 最基本的使用示例如:

1
2
3
4
use Test::Simple tests => 2;

ok( 1 + 1 == 2 );
ok( 2 + 2 == 5 );

ok() 的参数是 true 值, 则 the test passes, 如果是 false, 则 fails.

输出为:

1
2
3
4
5
1..2
ok 1
not ok 2
# Failed test at test.pl line 5.
# Looks like you failed 1 test of 2.

1..2 表明, 一共要进行 2 个测试, 序号从 1 开始.

加上描述信息

也可以给每一个 test 加上 describtion 信息 (通过传递给 ok() 第二个参数):

1
2
3
4
5
6
use Test::Simple tests => 2;
use Date::ICal;

my $ical = Date::ICal->new;
ok( defined $ical, 'new() returned something' );
ok( $ical->isa('Date::ICal'), "and it's the right class" );

Test::More

Test::More 可以完成所有 Test::Simple 的工作, 且额外添加了其他功能.

is() 函数(注意语法和 ok() 不同), 其还会给出错误信息:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
use Test::More tests => 8;

use Date::ICal;

$ical = Date::ICal->new( year => 1964, month => 10, day => 16,
hour => 16, min => 12, sec => 47,
tz => '0530' );

ok( defined $ical, 'new() returned something' );
ok( $ical->isa('Date::ICal'), " and it's the right class" );
is( $ical->sec, 47, ' sec()' );
is( $ical->min, 12, ' min()' );
is( $ical->hour, 16, ' hour()' );
is( $ical->day, 17, ' day()' );
is( $ical->month, 10, ' month()' );
is( $ical->year, 1964, ' year()' );

用来检测数组的长度如:

1
is( @foo, 5, 'foo has 5 elements' );

用 plan() 函数计算 tests 个数

1
2
3
4
5
6
7
8
9
use Test::More;
use Date::ICal;

my %ICal_Dates = (
...same as before...
);

# For each key in the hash we're running 8 tests.
plan tests => keys(%ICal_Dates) * 8;

使用 done_testing() 不需计算 tests 个数

当不使用 plan 时, 则使用 done_testing():

1
2
3
4
5
use Test::More;   # instead of tests => 32

... # tests here

done_testing(); # reached the end safely

此时不必手动计算.

跳过一段测试

使用 skip() 函数以及配合一个 code block, 标签为 SKIP:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
use Test::More tests => 7;
use Date::ICal;

# Make sure epoch time is being handled sanely.
my $t1 = Date::ICal->new( epoch => 0 );
is( $t1->epoch, 0, "Epoch time of 0" );

SKIP: {
skip('epoch to ICal not working on Mac OS', 6)
if $^O eq 'MacOS';

is( $t1->ical, '19700101Z', " epoch to ical" );

is( $t1->year, 1970, " year()" );
is( $t1->month, 1, " month()" );
is( $t1->day, 1, " day()" );

# like the tests above, but starting with ical instead of epoch
my $t2 = Date::ICal->new( ical => '19700101Z' );
is( $t2->ical, '19700101Z', "Start of epoch in ICal notation" );

is( $t2->epoch, 0, " and back to ICal" );
}

此时在 MacOS 上运行的输出为:

1
2
3
4
5
6
7
8
1..7
ok 1 - Epoch time of 0
ok 2 # skip epoch to ICal not working on Mac OS
ok 3 # skip epoch to ICal not working on Mac OS
ok 4 # skip epoch to ICal not working on Mac OS
ok 5 # skip epoch to ICal not working on Mac OS
ok 6 # skip epoch to ICal not working on Mac OS
ok 7 # skip epoch to ICal not working on Mac OS

Perl-Test-系列模块
http://example.com/2024/04/23/Perl-Test-系列模块/
作者
Jie
发布于
2024年4月23日
许可协议