本教程與PHP HTTP客戶端Guzzle一起演示了單元測試。 我們將探索三種方法:使用模擬響應文件的手工製作的自定義響應,並使用模擬響應來招募服務器。 ServiceClient
密鑰概念:
使用GuzzlePHP進行有效的單位測試涉及使用作曲家,配置Phpunit和創建測試類。ServiceClient
本教程假設對作曲家的熟悉程度。 文件應包括:
composer.json
>運行
{ "require": { "php": ">=5.3.3" }, "require-dev": { "phpunit/phpunit": "4.0.*", "guzzle/guzzle": "~3.7" } }
創建一個composer install
>:tests
>>>>>
bootstrap.php
phpunit.xml.dist
:
bootstrap.php
<?php error_reporting(E_ALL | E_STRICT); require dirname(__DIR__) . '/vendor/autoload.php';
phpunit.xml.dist
<?xml version="1.0" encoding="UTF-8"?> <phpunit bootstrap="./bootstrap.php" colors="true"> <testsuites> <testsuite name="Guzzle Tests"> <directory suffix="Test.php"></directory> </testsuite> </testsuites> </phpunit>
>
SitePointGuzzleTest.php
tests
<?php use Guzzle\Tests\GuzzleTestCase; use Guzzle\Plugin\Mock\MockPlugin; use Guzzle\Http\Message\Response; use Guzzle\Http\Client as HttpClient; use Guzzle\Service\Client as ServiceClient; use Guzzle\Http\EntityBody; class SitePointGuzzleTest extends GuzzleTestCase { protected $_client; }
然後,教程然後詳細介紹了嘲笑測試響應的三種方法,每個方法都有代碼示例和斷言。 這些示例演示瞭如何測試響應的各個方面,包括狀態代碼,標題和身體內容。 該教程還涉及異步請求測試和異常處理。 每種方法的完整代碼示例(手工製作的響應,模擬文件和招呼服務器)在GITHUB上的原始文章的源代碼中提供(原始文章中提供的鏈接)。
常見問題(常見問題解答):ServiceClient
>
使用
。>將guzzlephp與phpunit集成。
MockHandler
>測試異步請求。 以上是用guzzle進行單位測試的詳細內容。更多資訊請關注PHP中文網其他相關文章!