本教程与PHP HTTP客户端Guzzle一起演示了单元测试。 我们将探索三种方法:使用模拟响应文件的手工制作的自定义响应,并使用模拟响应来招募服务器。ServiceClient
密钥概念:
使用GuzzlePHP进行有效的单位测试涉及使用作曲家,配置Phpunit和创建测试类。ServiceClient
本教程假设对作曲家的熟悉程度。 文件应包括:
composer.json
>运行
<code class="language-json">{ "require": { "php": ">=5.3.3" }, "require-dev": { "phpunit/phpunit": "4.0.*", "guzzle/guzzle": "~3.7" } }</code>>和
创建一个composer install
>:tests
>>>>>
bootstrap.php
phpunit.xml.dist
:
bootstrap.php
<code class="language-php"><?php error_reporting(E_ALL | E_STRICT); require dirname(__DIR__) . '/vendor/autoload.php';</code>
phpunit.xml.dist
<code class="language-xml"><?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></code>>目录中:
>
SitePointGuzzleTest.php
tests
<code class="language-php"><?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; }</code>
然后,教程然后详细介绍了嘲笑测试响应的三种方法,每个方法都有代码示例和断言。 这些示例演示了如何测试响应的各个方面,包括状态代码,标题和身体内容。 该教程还涉及异步请求测试和异常处理。 每种方法的完整代码示例(手工制作的响应,模拟文件和招呼服务器)在GITHUB上的原始文章的源代码中提供(原始文章中提供的链接)。
常见问题(常见问题解答):ServiceClient
>
使用
。>将guzzlephp与phpunit集成。
MockHandler
>测试异步请求。以上是用guzzle进行单位测试的详细内容。更多信息请关注PHP中文网其他相关文章!