@@ -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
@@ -65,6 +72,27 @@ certain responses::
65
72
}
66
73
}
67
74
75
+ Or set a default response::
76
+
77
+ use Http\Mock\Client;
78
+
79
+ class YourTest extends \PHPUnit_Framework_TestCase
80
+ {
81
+ public function testClientReturnsResponse()
82
+ {
83
+ $client = new Client();
84
+
85
+ $response = $this->getMock('Psr\Http\Message\ResponseInterface');
86
+ $client->setDefaultResponse($response);
87
+
88
+ // $firstRequest and $secondRequest are instances of Psr\Http\Message\RequestInterface
89
+ $firstReturnedResponse = $client->sendRequest($firstRequest);
90
+ $secondReturnedResponse = $client->sendRequest($secondRequest);
91
+ $this->assertSame($response, $firstReturnedResponse);
92
+ $this->assertSame($response, $secondReturnedResponse);
93
+ }
94
+ }
95
+
68
96
To fake an exception being thrown::
69
97
70
98
use Http\Mock\Client;
@@ -87,4 +115,31 @@ To fake an exception being thrown::
87
115
}
88
116
}
89
117
118
+ Or set a default exception::
119
+
120
+ use Http\Mock\Client;
121
+
122
+ class YourTest extends \PHPUnit_Framework_TestCase
123
+ {
124
+ /**
125
+ * @expectedException \Exception
126
+ */
127
+ public function testClientThrowsException()
128
+ {
129
+ $client = new Client();
130
+
131
+ $exception = new \Exception('Whoops!');
132
+ $client->setDefaultException($exception);
133
+
134
+ $response = $this->getMock('Psr\Http\Message\ResponseInterface');
135
+ $client->addResponse($response);
136
+
137
+ // $firstRequest and $secondRequest are instances of Psr\Http\Message\RequestInterface
138
+ // The first request will returns the added response.
139
+ $firstReturnedResponse = $client->sendRequest($firstRequest);
140
+ // There is no more added response, the default exception will be thrown.
141
+ $secondReturnedResponse = $client->sendRequest($secondRequest);
142
+ }
143
+ }
144
+
90
145
.. include :: includes/further-reading-async.inc
0 commit comments