|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace unit; |
| 4 | + |
| 5 | +use PHPUnit\Framework\Attributes\DataProvider; |
| 6 | +use PHPUnit\Framework\Attributes\Test; |
| 7 | +use PHPUnit\Framework\TestCase; |
| 8 | +use rcsofttech85\FileHandler\Exception\FileHandlerException; |
| 9 | +use rcsofttech85\FileHandler\JsonFileHandler; |
| 10 | + |
| 11 | +class JsonFileHandlerTest extends TestCase |
| 12 | +{ |
| 13 | + private JsonFileHandler|null $jsonFileHandler; |
| 14 | + |
| 15 | + public static function setUpBeforeClass(): void |
| 16 | + { |
| 17 | + parent::setUpBeforeClass(); |
| 18 | + |
| 19 | + $content = '[ |
| 20 | + { |
| 21 | + "title": "The Catcher in the Rye", |
| 22 | + "author": "J.D. Salinger", |
| 23 | + "published_year": 1951 |
| 24 | + }, |
| 25 | + { |
| 26 | + "title": "To Kill a Mockingbird", |
| 27 | + "author": "Harper Lee", |
| 28 | + "published_year": 1960 |
| 29 | + }, |
| 30 | + { |
| 31 | + "title": "1984", |
| 32 | + "author": "George Orwell", |
| 33 | + "published_year": 1949 |
| 34 | + } |
| 35 | +] |
| 36 | +'; |
| 37 | + file_put_contents("book.json", $content); |
| 38 | + } |
| 39 | + |
| 40 | + public static function tearDownAfterClass(): void |
| 41 | + { |
| 42 | + parent::tearDownAfterClass(); |
| 43 | + unlink('book.json'); |
| 44 | + } |
| 45 | + |
| 46 | + /** |
| 47 | + * @return array<int,array<int, array<int, array<string, string>>>> |
| 48 | + */ |
| 49 | + public static function bookListProvider(): iterable |
| 50 | + { |
| 51 | + yield |
| 52 | + [ |
| 53 | + [ |
| 54 | + [ |
| 55 | + 'title' => 'The Catcher in the Rye', |
| 56 | + 'author' => 'J.D. Salinger', |
| 57 | + 'published_year' => '1951' |
| 58 | + ], |
| 59 | + [ |
| 60 | + 'title' => 'To Kill a Mockingbird', |
| 61 | + 'author' => 'Harper Lee', |
| 62 | + 'published_year' => '1960' |
| 63 | + ], |
| 64 | + [ |
| 65 | + 'title' => '1984', |
| 66 | + 'author' => 'George Orwell', |
| 67 | + 'published_year' => '1949' |
| 68 | + ], |
| 69 | + |
| 70 | + |
| 71 | + ] |
| 72 | + |
| 73 | + ]; |
| 74 | + } |
| 75 | + |
| 76 | + /** |
| 77 | + * @param array<int,array<string,string>> $book |
| 78 | + * @return void |
| 79 | + * @throws FileHandlerException |
| 80 | + */ |
| 81 | + #[Test] |
| 82 | + #[DataProvider('bookListProvider')] |
| 83 | + public function jsonFormatToArray(array $book): void |
| 84 | + { |
| 85 | + $data = $this->jsonFileHandler->toArray('book.json'); |
| 86 | + |
| 87 | + $this->assertSame(3, count($data)); |
| 88 | + $this->assertEquals($data, $book); |
| 89 | + } |
| 90 | + |
| 91 | + protected function setUp(): void |
| 92 | + { |
| 93 | + parent::setUp(); |
| 94 | + $this->jsonFileHandler = new JsonFileHandler(); |
| 95 | + } |
| 96 | + |
| 97 | + protected function tearDown(): void |
| 98 | + { |
| 99 | + parent::tearDown(); |
| 100 | + |
| 101 | + $this->jsonFileHandler = null; |
| 102 | + } |
| 103 | +} |
0 commit comments