@@ -43,6 +43,13 @@ To make assertions::
43
43
Fake Responses and Exceptions
44
44
-----------------------------
45
45
46
+ By default, the mock client returns an empty response with status 200.
47
+ You can set responses and exceptions the mock client should return / throw.
48
+ You can set several exceptions and responses, to have the client first throw
49
+ each exception once and then each response once on subsequent calls to send().
50
+ Additionally you can set a default response or a default exception to be used
51
+ instead of the empty response.
52
+
46
53
Test how your code behaves when the HTTP client throws exceptions or returns
47
54
certain responses::
48
55
@@ -63,6 +70,27 @@ certain responses::
63
70
}
64
71
}
65
72
73
+ Or set a default response::
74
+
75
+ use Http\Mock\Client;
76
+
77
+ class YourTest extends \PHPUnit_Framework_TestCase
78
+ {
79
+ public function testClientReturnsResponse()
80
+ {
81
+ $client = new Client();
82
+
83
+ $response = $this->getMock('Psr\Http\Message\ResponseInterface');
84
+ $client->setDefaultResponse($response);
85
+
86
+ // $firstRequest and $secondRequest are instances of Psr\Http\Message\RequestInterface
87
+ $firstReturnedResponse = $client->sendRequest($firstRequest);
88
+ $secondReturnedResponse = $client->sendRequest($secondRequest);
89
+ $this->assertSame($response, $firstReturnedResponse);
90
+ $this->assertSame($response, $secondReturnedResponse);
91
+ }
92
+ }
93
+
66
94
To fake an exception being thrown::
67
95
68
96
use Http\Mock\Client;
@@ -84,4 +112,31 @@ To fake an exception being thrown::
84
112
}
85
113
}
86
114
115
+ Or set a default exception::
116
+
117
+ use Http\Mock\Client;
118
+
119
+ class YourTest extends \PHPUnit_Framework_TestCase
120
+ {
121
+ /**
122
+ * @expectedException \Exception
123
+ */
124
+ public function testClientThrowsException()
125
+ {
126
+ $client = new Client();
127
+
128
+ $exception = new \Exception('Whoops!');
129
+ $client->setDefaultException($exception);
130
+
131
+ $response = $this->getMock('Psr\Http\Message\ResponseInterface');
132
+ $client->addResponse($response);
133
+
134
+ // $firstRequest and $secondRequest are instances of Psr\Http\Message\RequestInterface
135
+ // The first request will returns the added response.
136
+ $firstReturnedResponse = $client->sendRequest($firstRequest);
137
+ // There is no more added response, the default exception will be thrown.
138
+ $secondReturnedResponse = $client->sendRequest($secondRequest);
139
+ }
140
+ }
141
+
87
142
.. include :: includes/further-reading-async.inc
0 commit comments