【发布时间】:2017-06-27 16:45:37
【问题描述】:
有没有办法在 Guzzle 中模拟响应和请求?
我有一个发送一些请求的类,我想测试一下。
在 Guzzle doc 中,我找到了一种如何分别模拟响应和请求的方法。但是我怎样才能将它们结合起来呢?
因为,如果使用历史堆栈,会费力地尝试发送真正的请求。 而且签证诗,当我模拟响应处理程序无法测试请求时。
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'));
}
//...
}
【问题讨论】:
-
发布一些代码。描述相当混乱。模拟请求有什么意义?您在测试自定义处理程序吗?
-
我已经更新了代码@AlexBlex。通过一个模拟响应的示例,在文档中我们可以如何检查请求。问题,我该如何混合这个docs.guzzlephp.org/en/latest/testing.html#mock-handler 和这个docs.guzzlephp.org/en/latest/testing.html#history-middleware
-
$response = $this->sendRequest('PUT', '/users', ['body' => $body];没有尾括号。而'lang' = 'ru'应该是'lang' => 'ru'
标签: php unit-testing guzzle6 guzzle