以前想利用js單元測試框架測試接口, 但找了半天都是模擬ajax請求方式測試的.(jest框架).因此想到了利用php來實現.php
phpunit 地址:https://phpunit.de/manual/current/zh_cn/installation.html#installation.optional-packageshtml
guzzle 地址:https://github.com/guzzle/guzzlegit
1.phpunit須要php5.6環境才行. github
2.guzzle 解壓時須要 zlib. 用brew安裝.ajax
如下時測試代碼:
a.phpjson
require 'vendor/autoload.php'; class LoginTest extends PHPUnit_Framework_TestCase { //只是試試phpunit功能 public function testNormal() { $expected = 1; $actual = 1; $this->assertEquals($expected,$actual); } //測試api public function testSend(){ $client = new GuzzleHttp\Client(); $res = $client->request('GET', 'https://developer.github.com/v3/', [ ]); echo $res->getStatusCode(); // 200 echo $res->getHeaderLine('content-type'); // 'application/json; charset=utf8' echo $res->getBody(); $this->assertEquals(200, $res->getStatusCode()); } } ?>
而後在當前目錄 運行api
$ phpunit a.php
說明: guzzle安裝必須和測試代碼在同目錄中
app
Time: 7.14 seconds, Memory: 11.75Mb OK (2 tests, 2 assertions) antztekiMacBook-Pro:php_test antz$