qileilove

blog已经转移至github,大家请访问 http://qaseven.github.io/

Nginx单元测试自动化浅析之二-Test::More用法

 Perl 提供测试的基础模块是Test::More ,该包能提供测试用例的执行以及测试的断言。Test::Unit测试框架以及Test::Nginx测试框架都是基于该模块创建的。接下来介绍该模块常用的使用。

  1、导入包的方式

  use Test::More;

  同时Test::More需要事先申明需要测试的 testcase 的个数,声明方式如下:

  use Test::More tests => 2;

  这表示在该模块中有两个测试用例被执行。

  有时候,你不知道有多少测试用例会被执行,可以用这个方法:

  use Test::More;   # see done_testing()

  ……

  执行测试用例

  ……

  done_testing(); or done_testing($number_of_tests_run);

  2、常用 Test::More 断言方法:

  ok

  ok($succeeded, $test_name);

  该方法用来判断测试成功或者失败。第一个参数为判断参数,第二个参数为测试用例的名字。当$succeeded 为定义变量的变量非0、非空或者,则为成功,否则为失败。使用方式如下:

    ok( $exp{9} == 81,                   'simple exponential' );
    ok( Film->can('db_Main'),            'set_db()' );
    ok( $p->tests == 4,                  'saw tests' );
    ok( !grep !defined $_, @items,       'items populated' );

  is/isnt

is  ( $got, $expected, $test_name );
is  ( $got, $expected, $test_name );

  is() 和 isnt()函数与ok()函数的功能类似。is() 和 isnt()对是对比两个参数是否相等,若相等该测试用例就成功,否则失败。isnt()函数与is()论断结果相反。用法:

    # Is the ultimate answer 42?
is( ultimate_answer(), 42,          "Meaning of Life" );
 
    # $foo isn't empty
    isnt( $foo, '',     "Got some foo" );

  相当于ok()函数:

    ok( ultimate_answer() eq 42,        "Meaning of Life" );
    ok( $foo ne '',     "Got some foo" );

  注意:undef 只会匹配undef。

  Like/ unlike

like( $got, qr/expected/, $test_name );
unlike( $got, qr/expected/, $test_name );

  该函数和ok()函数类似,不同的是第二个参数可以为正则表达式qr/expected/。unlike()为like()函数的相反结果。用法:

like($got, qr/expected/, 'this is like that');

  类似于:

ok( $got =~ /expected/, 'this is like that');

  cmp_ok

cmp_ok( $got, $op, $expected, $test_name );

  cmp_ok()函数类似于ok() 和 is()。该方法还提供加入比较操作符的功能,用法。

cmp_ok( $got, 'eq', $expected, 'this eq that' );
cmp_ok( $got, '==', $expected, 'this == that' );
cmp_ok( $got, '&&', $expected, 'this && that' );

  3、常用显示测试诊断结果的方式:

  当测试用例运行失败的时候,经常是需要测试人员去debug排查失败的原因。该框架提供一些方法来提供只有当测试失败的时候才打印出失败信息的方式。

  diag

diag(@diagnostic_message);

  该函数保证打印一个诊断信息时不会干扰测试输出. 保证只有测试失败的时候才打印出信息。使用方式如下:

ok( grep(/foo/, @users), "There's a foo user" ) or
diag("Since there's no foo, check that /etc/bar is set up right");

  explain

my @dump = explain @diagnostic_message;

  该函数通过一种人可以阅读的格式输出任何引用指向的内容。通常和diag()函数一起使用。

相关链接:

Nginx 单元测试自动化浅析之一-Test::Nginx源码分析和使用

posted on 2013-06-17 10:27 顺其自然EVO 阅读(518) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航:
 
<2013年6月>
2627282930311
2345678
9101112131415
16171819202122
23242526272829
30123456

导航

统计

常用链接

留言簿(55)

随笔分类

随笔档案

文章分类

文章档案

搜索

最新评论

阅读排行榜

评论排行榜