最近尝试整合对接Walmart的API(其实就是把以前写的业务代码抽象成松散的模块,以便更好地调用),也把这些开源到了Github上https://github.com/FlyingWings/WalmartInterface,虽然现在只有V0.1版本,也只整合了GET方法;但是在实现过程中,逐步尝到了单元测试的甜头,于是果断开个新坑,介绍一下PHPunit的使用。
PHPunit作为一个测试框架,是xUnit架构在PHP语言中的一个实现,专注于单元测试+代码覆盖率;故而我们可以用它来做单元测试,并产生代码覆盖率报告。
建议通过Composer安装,直接composer require phpunit/phpunit即可,当然也可以通过制定版本,不过默认情况下会根据本地PHP版本来选择安装的版本,所以一般使用时直接执行上述指令即可
安装后,会在当前目录的vendor/bin/下生成一个名为phpunit的可执行文件,直接./vendor/bin/phpunit即可运行;而传入文件名或测试类名(一般测试类名与文件名相同[除扩展名])后,即可自动开始测试流程;
PHPUnit在编写测试用例时,以类为测试成员,以函数为基本单元,而各函数间通过标记依赖关系加以传值,这边通过一段示例来简要介绍一些常用的测试方式:
use PHPUnit\Framework\TestCase;//引入Framework下TestCase类 class WalmartFeaturesGetTest extends TestCase{ // 测试成员必须继承TestCase抽象类(当然也可以再继承) public function testAccountExists(){ // 测试函数,以test开头 global $config_array; //测试数组是否为空 $this->assertNotEmpty($config_array); $wal_account = new libraries\WalmartAccount($config_array); // 测试对象是否含有指定属性 $this->assertObjectHasAttribute("shop_name", $wal_account); // 返回指定值 return $wal_account; } /** * @depends testAccountExists * 这里通过@depends标记,将testAccountExists的返回值作为本函数的输入 */ public function testGetAllFeedStatus(\libraries\WalmartAccount $account){ $res = libraries\WalmartFeatures::getAllFeedStatus($account); $this->assertNotNull($res);//测试非空 $this->assertObjectHasAttribute("results", $res); } /** * @depends testAccountExists * 同上,利用依赖获取另一个函数的返回值 */ public function testGetFeedItemsStatus(\libraries\WalmartAccount $account){ // 故意传一个错误值,期望返回值中带有error $feedId = "tafdsfasf"; $res = \libraries\WalmartFeatures::getFeedItemsStatus($account, $feedId); $this->assertObjectHasAttribute("error", $res);// If having it, means meeting an error // 这次传一个正确值,期望返回正确状态 $feedId = '87E2CB2195AD40E23C9423912A8DBDA4@AQMBAQA';// An Real Feed id $res = \libraries\WalmartFeatures::getFeedItemsStatus($account, $feedId); $this->assertObjectNotHasAttribute("error", $res);// If having it, means meeting an error $this->assertObjectHasAttribute("feedStatus", $res); }}
在上面的测试例子中,有以下几个要点:
测试的依赖关系
public function testEmpty(){ $a = []; $this->assertEmpty($a); return $a; } public function testEmpty2(){ $b = []; $this->assertEmpty($b); return $b; } /** * @depends testEmpty * @depends testEmpty2 * 依次声明依赖 */ public function testUseful($a, $b){ $this->assertEmpty($a); $this->assertEmpty($b); $this->assertEquals($a, $b); }
测试所用的函数
本节中简单介绍了PHPUnit的应用场景,并以API调用作为例子,给出了测试函数间依赖调用的使用方式;下一节中将介绍其他的测试情况,如异常,错误,输出等,以及代码覆盖率的测试用法,敬请期待。 本文所使用PHP环境为PHP5.6.30, PHPUnit版本为4.8,请根据本地的PHP版本配置自己的PHPUnit版本,以及,一些测试函数在不同版本中会有不同,敬请谅解;
作者:掠影(萨秋)
转载请联系原作者
邮件ryoalex@foxmail.com