有没有办法在Guzzle中模拟响应和请求?
我有一个类发送一些请求,我想要测试。
在Guzzle doc 中,我找到了一种分别模拟响应和请求的方法。但是如何将它们组合起来呢?
因为,如果使用历史记录堆栈,Guzzle会尝试发送真实请求。反之亦然,当我模拟响应处理程序时,无法测试请求。
其中,link1需要翻译成对应的链接文字。
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'));
}
//...
}
$response = $this->sendRequest('PUT', '/users', ['body' => $body];
No trailing bracket.And
'lang' = 'ru'
should be'lang' => 'ru'
- Serhii Shliakhov