diff --git a/Server/App/Model/Product.php b/Server/App/Model/Product.php index c55fb3f..d47a012 100644 --- a/Server/App/Model/Product.php +++ b/Server/App/Model/Product.php @@ -28,13 +28,13 @@ public function __construct(ContainerInterface $container) $this->db = $container->get(Database::class); } - public function get(int $productId): stdClass + public function get(int $productId): ?stdClass { $stmt = $this->db->prepare(self::QUERY_GET_PRODUCT); $stmt->bindValue('productId', $productId, PDO::PARAM_INT); $stmt->execute(); - return $stmt->fetchObject(); + return $stmt->fetchObject() ?: null; } public function search(string $keywords, int $offset = null, int $limit = null): array diff --git a/Test/Server/App/Model/ProductTest.php b/Test/Server/App/Model/ProductTest.php new file mode 100644 index 0000000..816db14 --- /dev/null +++ b/Test/Server/App/Model/ProductTest.php @@ -0,0 +1,40 @@ +setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + $db->exec('CREATE TABLE product (id INTEGER PRIMARY KEY, product_name TEXT)'); + $db->exec("INSERT INTO product VALUES (1, 'Apple')"); + $container = new class($db) implements ContainerInterface { + private $db; + public function __construct(PDO $db) { $this->db = $db; } + public function get($id) { return $this->db; } + public function has($id): bool { return true; } + }; + return new Product($container); + } + + public function testExistingProductRetainsItsData(): void + { + $product = $this->model()->get(1); + self::assertSame('Apple', $product->product_name); + } + + public function testMissingProductCanBeHandledByTheController(): void + { + self::assertNull($this->model()->get(999)); + } +}