php - 在 Guzzle 中同时模拟响应和使用历史中间件

标签 php unit-testing guzzle6 guzzle

有什么方法可以在 Guzzle 中模拟响应和请求吗?

我有一个发送一些请求的类,我想测试一下。

在 Guzzle doc我找到了一种方法如何分别模拟响​​应和请求。但是我怎样才能将它们结合起来呢?

因为,如果使用历史堆栈,guzzle 会尝试发送真实请求。 反之亦然,当我模拟响应处理程序无法测试请求时。

class MyClass {

     public function __construct($guzzleClient) {

        $this->client = $guzzleClient;

    }

    public function registerUser($name, $lang)
    {

           $body = ['name' => $name, 'lang' = $lang, 'state' => 'online'];

           $response = $this->sendRequest('PUT', '/users', ['body' => $body];

           return $response->getStatusCode() == 201;        
    }

   protected function sendRequest($method, $resource, array $options = [])
   {

       try {
           $response = $this->client->request($method, $resource, $options);
       } catch (BadResponseException $e) {
           $response = $e->getResponse();
       }

       $this->response = $response;

      return $response;
  }

}

测试:

class MyClassTest {

  //....
 public function testRegisterUser()

 { 

    $guzzleMock = new \GuzzleHttp\Handler\MockHandler([
        new \GuzzleHttp\Psr7\Response(201, [], 'user created response'),
    ]);

    $guzzleClient = new \GuzzleHttp\Client(['handler' => $guzzleMock]);

    $myClass = new MyClass($guzzleClient);
    /**
    * But how can I check that request contains all fields that I put in the body? Or if I add some extra header?
    */
    $this->assertTrue($myClass->registerUser('John Doe', 'en'));


 }
 //...

}

最佳答案

@Alex Blex 非常亲密。

解决方案:

$container = [];
$history = \GuzzleHttp\Middleware::history($container);

$guzzleMock = new \GuzzleHttp\Handler\MockHandler([
    new \GuzzleHttp\Psr7\Response(201, [], 'user created response'),
]);

$stack = \GuzzleHttp\HandlerStack::create($guzzleMock);

$stack->push($history);

$guzzleClient = new \GuzzleHttp\Client(['handler' => $stack]);

关于php - 在 Guzzle 中同时模拟响应和使用历史中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42140692/

相关文章:

PHP/MySQL 帮助解析/提取分隔符和 ID

php - SQL JOIN 问题不从查询中返回用户详细信息并将它们打印在数组中

php - 结合 PHP 和 Jquery 的最佳实践是什么?

java - 使用 @PostConstruct 模拟类会导致初始化失败

php - 为什么我的 Guzzle 6 get() 调用返回空流?

composer-php - 通过 composer 与 guzzle 冲突的 plivo api 安装

php - 使用 Guzzle PHP 将文件分块上传到 URL 端点

php - 快速将虚拟数据插入mysql

c# - 最小起订量与 lambda 表达式?

unit-testing - 团队 build : Cannot find generated private accessor