simpletest-php单元测试框架的简单使用

最近部门在推行单元测试框架的时候,对C++有指定使用gtest,但对php并没有规定使用的框架,在试用了几个php单元测试框架后,认为simpletest这个框架最简单易用,而phpunit实在过于庞大与繁琐了。
这里简单说一下simpletest的使用。一个简单的unittest文件如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
define('BASE_PATH','/home/dantezhu/appbase/php/');
 
require_once BASE_PATH . '/simpletest/autorun.php';
 
class TestOfSite extends UnitTestCase
{
    function __construct()
    {
        parent::__construct();
    }
    function setUp() {}
    function tearDown() {}
 
    function test_case1()
    {
        $this->assertTrue(true);
    }
}
$test = &new TestOfSite();
//$test->run(new HtmlReporter());
$test->run(new TextReporter());

其中以test开头的函数即为每个testcase,而setUp和tearDown函数分别为每个testcase运行开始前和结束后会自动调用的函数,可以做一些初始化或者清理工作。

1
2
3
$test = &new TestOfSite();
//$test->run(new HtmlReporter());
$test->run(new TextReporter());

最后的这几句是用来执行单元测试,TextReporter会用文本方式展现,HtmlReporter会用html方式展现,对web调试比较友好。
下面就是几种基本的assert方法。

assertTrue($x)	Fail unless $x evaluates true
assertFalse($x)	Fail unless $x evaluates false
assertNull($x)	Fail unless $x is not set
assertNotNull($x)	Fail unless $x is set to something
assertIsA($x, $t)	Fail unless $x is the class or type $t
assertNotA($x, $t)	Fail unless $x is not the class or type $t
assertEqual($x, $y)	Fail unless $x == $y is true
assertNotEqual($x, $y)	Fail unless $x == $y is false
assertWithinMargin($x, $y, $margin)	Fail unless $x and $y are separated less than $margin
assertOutsideMargin($x, $y, $margin)	Fail unless $x and $y are sufficiently different
assertIdentical($x, $y)	Fail unless $x === $y for variables, $x == $y for objects of the same type
assertNotIdentical($x, $y)	Fail unless $x === $y is false, or two objects are unequal or different types
assertReference($x, $y)	Fail unless $x and $y are the same variable
assertCopy($x, $y)	Fail unless $x and $y are the different in any way
assertSame($x, $y)	Fail unless $x and $y are the same objects
assertClone($x, $y)	Fail unless $x and $y are identical, but separate objects
assertPattern($p, $x)	Fail unless the regex $p matches $x
assertNoPattern($p, $x)	Fail if the regex $p matches $x
expectError($e)	Triggers a fail if this error does not happen before the end of the test
expectException($e)	Triggers a fail if this exception is not thrown before the end of the test

整体来说,simpletest的很多思想和gtest不谋而合,比如说不用注册用例等。

详细的文档可以参见如下链接:
http://www.simpletest.org/en/first_test_tutorial.html





原创文章,版权所有。转载请注明:转载自Vimer的程序世界 [ http://www.vimer.cn ]

本文链接地址: http://www.vimer.cn/?p=1816

一个评论 在 “simpletest-php单元测试框架的简单使用”

我要评论

*

*