php单元测试之simpletest

了解单元测试

        单元测试是由程序员自己来完成,最终受益的也是程序员自己。可以这么说,程序员有责任编写功能代码,同时也就有责任为自己的代码编写单元测试。执行单元测试,就是为了证明这段代码的行为和我们期望的一致。

        在单元测试的过程中,第一步也是最重要的一步就是要理解我们要测试的单元原本要做什么,而不是他实际上做了什么,所以这就要求我们在开发代码的时候,每一个单元或者是每一个函数都要有一个概要的规格说明。

学习主要的php框架

        在PHP领域,单元测试的工具主要有PHPUNIT,PHPUNIT2和SimpleTest三种。其中PHPUNIT在功能上很简单,不算完善;PHPUNIT2是专门为PHP5写的单元 测试工具,在结构和功能上都向Junit看齐;而SimpleTest则是一套非常实用的测试工具,其中的webTest支持对web程序界面的测试,是 Easy最为推荐的一款测试工具。本次我主要就是学习了simpletest框架。

具体框架的使用

        Simpletest 使用起来非常的简单和方便,安装也很容易,只需网上下载安装包,然后解压在本地服务可以访问到的文件夹即可。

接下来就是它的主要功能:

1)有标准的输出

它的输出格式如下:


测试代码:

require_once('simpletest/autorun.php');//加载测试文件之前必须引入的框架入口文件

require_once('../classes/log.php');//要测试的类文件

class TestOfLogging extends UnitTestCase {

   function testLogCreatesNewFileOnFirstMessage() {

        @unlink('/temp/test.log');

       $log = new Log('/temp/test.log');

       $this->assertFalse(file_exists('/temp/test.log'));

       $log->message('Should write this to a file');

       $this->assertTrue(file_exists('/temp/test.log'));

    }

}

这里有几点说明:

1、必须引入框架入口文件 和要测试的文件

2、新建的类要继承UnitTestCase等类文件

3、新建的方法要以test开头

同时如果我们要测试多个类,可以将所有的测试类进行合并到一个文件

如:


class AllTests extends TestSuite

{

   public function __construct()

    {

       parent::__construct('All tests for SimpleTest ' . SimpleTest::getVersion());

       $this->addFile(__DIR__ . '/unit_tests.php');

       $this->addFile(__DIR__ . '/shell_test.php');


       /**

        * The "live" and "acceptance" tests require arunning local webserver on "localhost:8080".

        * We are using PHP's built-in webserver to serve the"test/site".

        * The start command for the server is: `php -S localhost:8080 -ttest/site`.

        */

       $this->addFile(__DIR__ . '/live_test.php');

       $this->addFile(__DIR__ . '/acceptance_test.php');

    }

}

2)可以进行类的模拟

主要代码如下:

require_once dirname(__FILE__) .'/mock_objects.php';

Mock::generate('Log');


class TestOfSessionLogging extendsUnitTestCase {


   function testLoggingInIsLogged() {

       $log = &new MockLog();

       $log->expectOnce('message', array('User fred logged in.'));

       $session_pool = &new SessionPool($log);

       $session_pool->logIn('fred');

    }

}

即我们可以模拟一个类Log,模拟的类名为MockLog,然后我们就可以像真实存在一个类MockLog一样来使用这个类。这样做的好处就是只专注我们需要测试的部分,并且不会因为其他的类代码的改变来影响我们的测试类。

3)可以进行网页测试

在SimpleTest中的Web测试是相当原始的,因为没有JavaScript。大多数其他浏览器操作都只是模拟请求和发生数据。


require_once('simpletest/autorun.php');

require_once('simpletest/web_tester.php');


class TestOfRankings extends WebTestCase {

   function testWeAreTopOfGoogle() {

       $this->get('http://google.com/');

       $this->setField('q', 'simpletest');

       $this->click("I'm Feeling Lucky");

       $this->assertTitle('SimpleTest - Unit Testing for PHP');

    }

}

该段代码就可以模拟google的搜索操作,并且来验证返回的title.

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容