phpunit:重拾PHPUnit

  想想上次用PHPUnit似乎是年多以前事情了那以后我直是SimpleTest忠实粉丝现在工作需要不得不重拾PHPUnit可惜对于它记忆都已经模糊了切都只好从头再来顺便也笔记免得以后忘记

  以下操作均以Windows操作系统为例:

  安装好PHP环境后先安装PEAR思路方法很简单只要在命令行执行go-pear.bat脚本就OK了接下来使用PEAR来安装PHPUnit:

  pear channel-discover pear.phpunit.de

  pear phpunit/PHPUnit

  提示:手动安装PEAR也是种思路方法不过除非网络有问题否则不推荐手动安装方式不然还得自己设定很多东西容易出错

  然后记得把PEAR路径添加到_path中(比如说_path="C:/php/pear")

  最后修改操作系统PATH环境变量(比如说path=c:/php)

  为了更好效果推荐给PHP加装Xdebug扩展相关php.ini修改如下:

  [Xdebug]

  zend_extension_ts="c:/php/ext/php_xdebug.dll"

  xdebug.profiler_enable=on

  xdebug.profiler_output_dir="C:/xdebug"

  xdebug.trace_output_dir="C:/xdebug"

  此扩展并不是必须但是有了它PHPUnit可以测试代码覆盖率而且在开发阶段配合WinCacheGrind还能更直观了解脚本性能

  到这里我们准备工作基本完成了下面运行个简单Demo来检验下效果:

  编辑文件ArrayTest.php:

<?php 
ArrayTest extends PHPUnit_Framework_TestCase 
{ 
   public function testNewArrayIsEmpty 
   { 
    // Create the Array fixture. 
    $fixture = Array; 
    // Assert that the size of the Array fixture is 0. 
    $this->assertEquals(0, ($fixture)); 
   } 
   public function testArrayContainsAnElement 
   { 
    // Create the Array fixture. 
    $fixture = Array; 
    // Add an element to the Array fixture. 
    $fixture = 'Element'; 
    // Assert that the size of the Array fixture is 1. 
    $this->assertEquals(1, ($fixture)); 
   } 
} 
?>


  然后在命令行下运行:phpunit ArrayTest就可以看到相应结果了不过在命令行下敲字母总是让人不爽我们可以让这个过程更有趣以EditPlus编辑器为例:

  Tools -> Configure User Tools -> Add Tool

  然后设定:

Menu Text         : PHPUnit
Command          : C:phpphpunit.bat
Argument          : $(FileNameNoExt)
InitialDirecotry      : $(FileDir)


  搞定了如果这是你EditPlus中第个UserTool那么当你编辑好你Test类文件后只要按下Ctrl + 1就可以调出相应命令行运行界面了

  末了再唠叨几句编写测试用例看着是个没啥技术含量活儿不过实际有很多讲究比如说Mock使用这些说起来就多了不说也罢

Tags:  phpunit2 phpunit

延伸阅读

最新评论

发表评论