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' ); |
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()函數一起使用。
相關鏈接: