guzzle.png

本文将介绍Guzzle,Guzzle在单元测试中的使用。

来自Guzzle中文文档的解释:

Guzzle是一个PHP的HTTP客户端,用来轻而易举地发送请求,并集成到我们的WEB服务上。

接口简单:构建查询语句、POST请求、分流上传下载大文件、使用HTTP cookies、上传JSON数据等等。

发送同步或异步的请求均使用相同的接口。

使用PSR-7接口来请求、响应、分流,允许你使用其他兼容的PSR-7类库与Guzzle共同开发。

抽象了底层的HTTP传输,允许你改变环境以及其他的代码,如:对cURL与PHP的流或socket并非重度依赖,非阻塞事件循环。

中间件系统允许你创建构成客户端行为。

$client = new GuzzleHttp\Client();

$res = $client->request('GET', 'https://api.github.com/user', [

'auth' => ['user', 'pass']

]);

echo $res->getStatusCode();

// "200"

echo $res->getHeader('content-type');

// 'application/json; charset=utf8'

echo $res->getBody();

// {"type":"User"...'

// 发送一个异步请求

$request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org');

$promise = $client->sendAsync($request)->then(function ($response) {

echo 'I completed! ' . $response->getBody();

});

$promise->wait();

安装Guzzle

使用composer安装

php composer.phar require guzzlehttp/guzzle:~6.0

或者编辑项目的composer.json文件,添加Guzzle作为依赖

{

"require": {

"guzzlehttp/guzzle": "~6.0"

}

}

执行 composer update

Guzzle基本使用

发送请求

use GuzzleHttp\Client;

$client = new Client([

// Base URI is used with relative requests

'base_uri' => 'http://httpbin.org',

// You can set any number of default request options.

'timeout' => 2.0,

]);

$response = $client->get('http://httpbin.org/get');

$response = $client->delete('http://httpbin.org/delete');

$response = $client->head('http://httpbin.org/get');

$response = $client->options('http://httpbin.org/get');

$response = $client->patch('http://httpbin.org/patch');

$response = $client->post('http://httpbin.org/post');

$response = $client->put('http://httpbin.org/put');

设置查询字符串

$response = $client->request('GET', 'http://httpbin.org?foo=bar');

或使用 query 请求参数来声明查询字符串参数:

$client->request('GET', 'http://httpbin.org', [

'query' => ['foo' => 'bar']

]);

设置POST表单

传入 form_params 数组参数

$response = $client->request('POST', 'http://httpbin.org/post', [

'form_params' => [

'field_name' => 'abc',

'other_field' => '123',

'nested_field' => [

'nested' => 'hello'

]

]

]);

使用响应

# 状态码

$code = $response->getStatusCode(); // 200

$reason = $response->getReasonPhrase(); // OK

# header

// Check if a header exists.

if ($response->hasHeader('Content-Length')) {

echo "It exists";

}

// Get a header from the response.

echo $response->getHeader('Content-Length');

// Get all of the response headers.

foreach ($response->getHeaders() as $name => $values) {

echo $name . ': ' . implode(', ', $values) . "\r\n";

}

# 响应体

$body = $response->getBody();

// Implicitly cast the body to a string and echo it

echo $body;

// Explicitly cast the body to a string

$stringBody = (string) $body;

// Read 10 bytes from the body

$tenBytes = $body->read(10);

// Read the remaining contents of the body as a string

$remainingBytes = $body->getContents();

安装PHPUnit

同Guzzle的安装, 也适用Composer工具。

composer global require "phpunit/phpunit=5.5.*"

或者在composer.json文件中声明对phpunit/phpunit的依赖

{

"require-dev": {

"phpunit/phpunit": "5.5.*"

}

}

执行安装

API 单元测试

我们在tests\unit\MyApiTest.php中定义了两个测试用例

class MyApiTest extends \PHPUnit_Framework_TestCase

{

protected $client;

public function setUp()

{

$this->client = new \GuzzleHttp\Client( [

'base_uri' => 'http://myhost.com',

'http_errors' => false, #设置成 false 来禁用HTTP协议抛出的异常(如 4xx 和 5xx 响应),默认情况下HTPP协议出错时会抛出异常。

]);

}

public function testAction1()

{

$response = $this->client->get('/api/v1/action1');

$body = $response->getBody();

//添加测试

$this->assertEquals(200, $response->getStatusCode());

$data = json_decode($body, true);

$this->assertArrayHasKey('errorno', $data);

$this->assertArrayHasKey('errormsg', $data);

$this->assertArrayHasKey('data', $data);

$this->assertEquals(0, $data['errorno']);

$this->assertInternalType('array', $data['data']);

}

public function testAction2()

{

$response = $this->client->post('/api/v1/action2', [

'form_params' => [

'name' => 'myname',

'age' => 20,

],

]);

$body = $response->getBody();

//添加测试

$this->assertEquals(200, $response->getStatusCode());

$data = json_decode($body, true);

$this->assertArrayHasKey('errorno', $data);

$this->assertArrayHasKey('errormsg', $data);

$this->assertArrayHasKey('data', $data);

$this->assertEquals(0, $data['errorno']);

$this->assertInternalType('array', $data['data']);

}

}

运行测试

在项目根目录执行命令

php vendor/bin/phpunit tests/unit/MyApiTest.php

总结

通过Guzzle强大的功能,可以方便进行API单元测试。大家可以查看Guzzle文档,详细了解Guzzle的使用。

参考文档

guzzle php,PHP中使用Guzzle进行API测试相关推荐

  1. 面对行业分析家和敏捷专家都认可的API测试,我们为什么会望而却步?

    转向微服务和API驱动的架构正在推动整个行业的重大创新,但也使企业面临隐患.人机界面(Web和移动UI)不再是主要业务风险所在.相反,最大的漏洞隐藏在API的非人机界面中. 因此,API测试已成为越来 ...

  2. PHP guzzle异步请求数据,怎么在PHP中使用Guzzle执行POST和GET请求

    怎么在PHP中使用Guzzle执行POST和GET请求 发布时间:2021-02-17 08:01:14 来源:亿速云 阅读:67 作者:Leah 怎么在PHP中使用Guzzle执行POST和GET请 ...

  3. PHP项目中使用Guzzle执行POST和GET请求

    以往在项目中要用到第三方接口时会用到封装好的curl执行请求,现在有了更好的解决方案--Guzzle. 下面是官方介绍: Guzzle是一个PHP的HTTP客户端,用来轻而易举地发送请求,并集成到我们 ...

  4. php:项目中使用Guzzle执行POST和GET请求

    以往在项目中要用到第三方接口时会用到封装好的curl执行请求,现在有了更好的解决方案--Guzzle. 下面是官方介绍: Guzzle是一个PHP的HTTP客户端,用来轻而易举地发送请求,并集成到我们 ...

  5. (四)Asp.net web api中的坑-【api的返回值】

    (四)Asp.net web api中的坑-[api的返回值] 原文:(四)Asp.net web api中的坑-[api的返回值] void无返回值 IHttpActionResult HttpRe ...

  6. 初学api测试_面向初学者的API-在此免费视频课程中学习如何使用API

    初学api测试 What exactly is an API? How do you use an API? We've just published a full beginner's course ...

  7. Struts2中Action访问Servlet API的三种方法

    Struts2的Action并未直接与任何Servlet API耦合,这是Struts2的一个改良之处,因为Action类不再与Servlet API耦合,能更轻松的测试该Action.但如何访问? ...

  8. struts2:在Action中使用Servlet的API,设置、读取各种内置对象的属性

    有两种方式可以实现在Action中使用Servlet的API.一种是使用org.apache.struts2.ServletActionContext类,另一种是使用com.opensymphony. ...

  9. 谈谈前后端分离实践中如何提升RESTful API开发效率

    点击上方"朱小厮的博客",选择"设为星标" 后台回复"书",获取推荐书籍 来源:33h.co/edZR 团队内部RestAPI开发采用设计驱 ...

  10. Pipelines - .NET中的新IO API指引(二)

    原文:Pipelines - a guided tour of the new IO API in .NET, part 2 作者:marcgravell 在上一章,我们讨论了以往的StreamAPI ...

最新文章

  1. java房源信息管理的代码_crawler4j源码学习(2):Ziroom租房网房源信息采集爬虫
  2. 内存分配,任意字节对齐
  3. promise用法_Promise的秘密
  4. VS2015调试程序
  5. ​【原型设计】8种原型设计工具介绍​
  6. 一位软件实施工程师的自述(转)
  7. python少儿编程008:海龟绘图画出奥运五连环!
  8. 等额本金和等额本息是怎么算出来的
  9. C++ 异常 0xC0000005 访问冲突,exit code 0xC0000005 的解决方法
  10. python字典函数大全_python字典介绍
  11. Java数据结构与算法———(8)单链表应用实例,删除节点,根据输入的整数
  12. 2022春秋杯-被带走的机密文件
  13. SHELL自动化运维
  14. 计算机联锁毕业设计目标,毕业设计论文-计算机联锁设计.doc
  15. Superscan功能介绍以及用Superscan测试、扫描开放端口
  16. HTML+CSS大作业——商城个人中心网站模板(56页) 学生HTML个人网页作业作品下载 个人主页博客网页设计制作 大学生个人网站作业模板 简单个人网页制作
  17. Jenkins打包IOS项目(疑难问题总结)
  18. 转载MTK通话背景音
  19. 近 100 个 Linux 常用命令大全
  20. c4d怎么导入图片描图建模_在CAD中如何直接利用图片进行描图?

热门文章

  1. 数量遗传学 第五章 双亲杂交后代数量性状均值和方差组成
  2. Android dex2oat命令参数解释
  3. pdf文件加水印输出图片
  4. Photoshop基础学习-修改图片文字
  5. 队列练习之Example004-设计一个循环队列,用 front 和 rear 分别作为队头和队尾指针,另外用一个标志 tag 表示队列是空还是不空
  6. 多家汽车金融公司拿下融担牌照,“助贷+融担”模式成主流
  7. Qt5.12.6 + VS2019添加图片资源文件
  8. 获取指定年月的月初跟月末的时间戳
  9. linux怎么进sda12,VMare12.0.1安装Ubuntu16.04.2遇到[sda] Assuming drive cache
  10. bucket name does not follow Amazon S3 standards