Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 83 additions & 0 deletions clients/mock-client.rst
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,89 @@ Or set a default exception::
}
}

Mocking request-dependent responses
-----------------------------------

You can mock responses and exceptions which are only used in certain requests
or act differently depending on the request.

To conditionally return a response when a request is matched::

use Http\Mock\Client;
use Psr\Http\Message\ResponseInterface;

class YourTest extends \PHPUnit_Framework_TestCase
{
/**
* @expectedException \Exception
*/
public function testClientThrowsException()
{
$client = new Client();

// $requestMatcher is an instance of Http\Message\RequestMatcher

$response = $this->createMock(ResponseInterface:class);
$client->on($requestMatcher, $response);

// $request is an instance of Psr\Http\Message\RequestInterface
$returnedResponse = $client->sendRequest($request);
}
}

Or for an exception::

use Http\Mock\Client;
use Exception;

class YourTest extends \PHPUnit_Framework_TestCase
{
public function testClientThrowsException()
{
$client = new Client();

// $requestMatcher is an instance of Http\Message\RequestMatcher

$exception = new \Exception('Whoops!');
$client->on($requestMatcher, $exception);

// $request is an instance of Psr\Http\Message\RequestInterface

$this->expectException(\Exception::class);
$returnedResponse = $client->sendRequest($request);
}
}

Or pass a callable, and return a response or exception based on the request::

use Http\Mock\Client;
use Psr\Http\Message\RequestInterface;

class YourTest extends \PHPUnit_Framework_TestCase
{
/**
* @expectedException \Exception
*/
public function testClientThrowsException()
{
$client = new Client();

// $requestMatcher is an instance of Http\Message\RequestMatcher

$client->on($requestMatcher, function (RequestInterface $request) {

// return a response
return $this->createMock('Psr\Http\Message\ResponseInterface');

// or an exception
return new \Exception('Whoops!');
});

// $request is an instance of Psr\Http\Message\RequestInterface
$returnedResponse = $client->sendRequest($request);
}
}


.. hint::

Expand Down