Guzzle에서 응답 및 요청을 모방 할 수있는 방법이 있습니까?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 코드를 업데이트했습니다. 모의 응답의 예제와 함께 문서에서 요청을 확인하는 방법을 확인할 수 있습니다. 질문, 어떻게이 http://docs.guzzlephp.org/en/latest/testing.html#mock-handler와이 http://docs.guzzlephp.org/ko/latest/testing.html#history- 미들웨어 – xAoc