系统分析与设计的课程大Project做完了,但是作为一个系统的软件流程,怎么能少了软件测试,有了软测,才是真正的软件工程。由于我们的课程项目使用的是php写的后台。而PHPUnit是一个非常好的php单元测试的工具。

       首先,要来安装phpunit,在linux或者unix下,先到官网下载 https://phpunit.de/

       下载下来后,命令行进入当前目录,执行如下的命令:


        看到这个基本就说明安装成功了。

        接下来,我们可以进行测试了。


例 1: 用 PHPUnit 测试数组操作

<?php
class StackTest extends PHPUnit_Framework_TestCase
{
    public function testPushAndPop()
    {
        $stack = array();
        $this->assertEquals(0, count($stack));

        array_push($stack, 'foo');
        $this->assertEquals('foo', $stack[count($stack)-1]);
        $this->assertEquals(1, count($stack));

        $this->assertEquals('foo', array_pop($stack));
        $this->assertEquals(0, count($stack));
    }
}
?>
然后在命令行执行如下所示:




例 2: 用 @depends 标注来表达依赖关系

<?php
class StackTest extends PHPUnit_Framework_TestCase
{
    public function testEmpty()
    {
        $stack = array();
        $this->assertEmpty($stack);

        return $stack;
    }

    /**
     * @depends testEmpty
     */
    public function testPush(array $stack)
    {
        array_push($stack, 'foo');
        $this->assertEquals('foo', $stack[count($stack)-1]);
        $this->assertNotEmpty($stack);

        return $stack;
    }

    /**
     * @depends testPush
     */
    public function testPop(array $stack)
    {
        $this->assertEquals('foo', array_pop($stack));
        $this->assertEmpty($stack);
    }
}
?>
然后在命令行执行如下所示:




例 3: 利用测试之间的依赖关系

<?php
class DependencyFailureTest extends PHPUnit_Framework_TestCase
{
    public function testOne()
    {
        $this->assertTrue(FALSE);
    }

    /**
     * @depends testOne
     */
    public function testTwo()
    {
    }
}
?>

命令后运行结果如下所示:

phpunit --verbose DependencyFailureTest
PHPUnit 4.7.0 by Sebastian Bergmann and contributors.

FS

Time: 0 seconds, Memory: 5.00Mb

There was 1 failure:

1) DependencyFailureTest::testOne
Failed asserting that false is true.

/home/sb/DependencyFailureTest.php:6

There was 1 skipped test:

1) DependencyFailureTest::testTwo
This test depends on "DependencyFailureTest::testOne" to pass.


FAILURES!
Tests: 1, Assertions: 1, Failures: 1, Skipped: 1.


Logo

更多推荐