pstephan1187/laravel-guzzler

一个封装Guzzle的包,可以方便地测试HTTP响应

v1.0.0 2017-06-16 21:38 UTC

This package is not auto-updated.

Last update: 2024-09-15 02:14:18 UTC


README

Laravel Guzzler是一个包,使得测试发送HTTP请求的应用逻辑变得简单。Guzzle包含测试请求的功能,但您通常需要在测试中从内部传递配置参数到Guzzle对象,这通常是不切实际的。这个包使这个过程变得非常简单

test_my_function_returns_client_id()
{
    Guzzler::respondWith(json_encode(['client_id' => 123]))->hijack();

    $client_id = myFunctionThatReturnsAClientIdFromAnApiRequest();

    $this->assertEquals(123, $client_id);
}

安装

composer require pstephan1187/laravel-guzzler

将服务提供者添加到您的应用程序配置文件中

Guzzler\GuzzlerServiceProvider::class,

可选地,添加外观(文档假设您会这样做)

'Guzzler' => Guzzler\Facades\Guzzler::class,

用法

在您通常使用 new GuzzleHttp\Client($params) 的任何地方,您将替换为 guzzle($params);

$client = guzzle(['base_uri' => 'https://www.mysite.com']);

当您需要测试方法时,您将拦截HTTP请求并返回一个自定义响应

Guzzler::respondWith($body, $status_code, $headers)->hijack();

您还可以链式调用多个响应

Guzzler::respondWith($body, $status_code, $headers)// gets returned the first time guzzle makes an HTTP request
    ->respondWith($second_body, $second_status_code, $second_headers)// gets returned the second time guzzle makes an HTTP request
    ->respondWith($third_body, $third_status_code, $third_headers)// gets returned the third time guzzle makes an HTTP request
    ->hijack();