Skip to content

Instantly share code, notes, and snippets.

@yehchge
Last active January 27, 2021 15:44
Show Gist options
  • Save yehchge/609cdff06fc7ac0ea37bec1484d5d0b4 to your computer and use it in GitHub Desktop.
Save yehchge/609cdff06fc7ac0ea37bec1484d5d0b4 to your computer and use it in GitHub Desktop.
phpunit PDOException Assert
<?php declare(strict_types=1);
use PHPUnit\Framework\TestCase;
class DBA
{
public function getRowCount($table)
{
$pdo = new PDO("mysql:host=localhost;dbname=test",'root','');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// try {
$res = $pdo->query("SELECT COUNT(1) FROM $table");
$count = $res->fetchColumn();
return $count;
// } catch (PDOException $e) {
// die($e->getMessage().PHP_EOL);
// }
}
}
class MyTest extends TestCase
{
public function testPDOException() : void
{
$pdo = new DBA();
// Assert
$this->expectException(PDOException::class);
// Act
$row = $pdo->getRowCount('guestbookerrrer');
}
}
@yehchge
Copy link
Author

yehchge commented Jan 27, 2021

add $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
run phpunit result:

PHPUnit 9.5.1 by Sebastian Bergmann and contributors.

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'test.guestbookerrrer' doesn't exist

@yehchge
Copy link
Author

yehchge commented Jan 27, 2021

must remove getRowCount try...catch , the phpunit test will can run ok. but .....

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment