|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Symfony\Component\HttpClient\Tests\Response; |
| 4 | + |
| 5 | +use PHPUnit\Framework\TestCase; |
| 6 | +use Symfony\Component\HttpClient\Exception\JsonException; |
| 7 | +use Symfony\Component\HttpClient\Response\MockResponse; |
| 8 | + |
| 9 | +/** |
| 10 | + * Test methods from Symfony\Component\HttpClient\Response\ResponseTrait. |
| 11 | + */ |
| 12 | +class MockResponseTest extends TestCase |
| 13 | +{ |
| 14 | + public function testToArray() |
| 15 | + { |
| 16 | + $data = ['color' => 'orange', 'size' => 42]; |
| 17 | + $response = new MockResponse(json_encode($data)); |
| 18 | + $response = MockResponse::fromRequest('GET', 'https://example.com/file.json', [], $response); |
| 19 | + |
| 20 | + $this->assertSame($data, $response->toArray()); |
| 21 | + } |
| 22 | + |
| 23 | + /** |
| 24 | + * @dataProvider toArrayErrors |
| 25 | + */ |
| 26 | + public function testToArrayError($content, $responseHeaders, $message) |
| 27 | + { |
| 28 | + $this->expectException(JsonException::class); |
| 29 | + $this->expectExceptionMessage($message); |
| 30 | + |
| 31 | + $response = new MockResponse($content, ['response_headers' => $responseHeaders]); |
| 32 | + $response = MockResponse::fromRequest('GET', 'https://example.com/file.json', [], $response); |
| 33 | + $response->toArray(); |
| 34 | + } |
| 35 | + |
| 36 | + public function toArrayErrors() |
| 37 | + { |
| 38 | + yield [ |
| 39 | + 'content' => '{}', |
| 40 | + 'responseHeaders' => ['content-type' => 'plain/text'], |
| 41 | + 'message' => 'Response content-type is "plain/text" while a JSON-compatible one was expected for "https://example.com/file.json".', |
| 42 | + ]; |
| 43 | + |
| 44 | + yield [ |
| 45 | + 'content' => 'not json', |
| 46 | + 'responseHeaders' => [], |
| 47 | + 'message' => 'Syntax error for "https://example.com/file.json".', |
| 48 | + ]; |
| 49 | + |
| 50 | + yield [ |
| 51 | + 'content' => '[1,2}', |
| 52 | + 'responseHeaders' => [], |
| 53 | + 'message' => 'State mismatch (invalid or malformed JSON) for "https://example.com/file.json".', |
| 54 | + ]; |
| 55 | + |
| 56 | + yield [ |
| 57 | + 'content' => '"not an array"', |
| 58 | + 'responseHeaders' => [], |
| 59 | + 'message' => 'JSON content was expected to decode to an array, string returned for "https://example.com/file.json".', |
| 60 | + ]; |
| 61 | + |
| 62 | + yield [ |
| 63 | + 'content' => '8', |
| 64 | + 'responseHeaders' => [], |
| 65 | + 'message' => 'JSON content was expected to decode to an array, integer returned for "https://example.com/file.json".', |
| 66 | + ]; |
| 67 | + } |
| 68 | +} |
0 commit comments