2017-02-09 1 views
2

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')); 


} 
//... 

} 
+0

포스트 일부 코드. 설명은 매우 혼란 스럽습니다. 조롱 요청의 요지는 무엇입니까? 커스텀 핸들러를 테스트하고 있습니까? –

+0

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

답변

2

@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]); 
1

첫째로, 당신은하지 모의 요청을한다. 요청은 프로덕션 환경에서 사용할 실제 요청입니다. 당신이 테스트를 실행 한 후 당신이 주장하는

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

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

$stack->push($history); 

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

$container 모든 거래를해야합니다 : 당신이 거기에 여러 핸들러를 밀어 수 있도록 모의 핸들러는, 실제로 스택입니다. 특정 테스트에서 - 단일 거래. $container[0]['response']에 미리 준비된 답변이 포함되어 있기 때문에 $container[0]['request']에 관심이 있으니 실제로 주장 할 내용은 없습니다.

+0

GuzzleHttp \ Handler \ MockHandler :: __ invoke()에 전달 된 인수 1은/vendor/guzzlehttp/guzzle/src /에서 호출 된 Closure의 인스턴스 인 Psr \ Http \ Message \ RequestInterface 인터페이스를 구현해야합니다. HandlerStack.php 199 라인에 정의되어 있습니다. – xAoc

+0

아, 죄송합니다. MockHandler가 스택을 생성하기 위해 팩토리를 사용해야한다는 사실을 잊어 버렸습니다. 답변을 업데이트했습니다. –

+1

당신이 직접 해결했다고 깨달았습니다. 잘 했어! –

관련 문제