Skip to content

Commit

Permalink
Added documentation for conditional mocks (#256)
Browse files Browse the repository at this point in the history
  • Loading branch information
adamquaile authored and dbu committed Mar 2, 2019
1 parent 2a31608 commit bfa9c56
Showing 1 changed file with 83 additions and 0 deletions.
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

0 comments on commit bfa9c56

Please sign in to comment.