I am start using PHPUnit for my projects and I need to test that some data is been stored successfully in the database.
My problem is that the PDO connection, which is created in a separate file with the name $connpdo, is not reachable. I really don’t get why.
This is my code:
<?php include_once("database_inc.php"); use PHPUnitFrameworkTestCase; function save_twins($auto_id = 412184){ global $connpdo; $query = "select quality_inspection from dqa_manifest_upload_rules where auto_id = $auto_id"; $stmt = $connpdo->query($query); $row = $stmt->fetch(PDO::FETCH_ASSOC); $quality = $row["quality_inspection"]; return $quality; } class Test_save_twins extends TestCase { public function testExamples() { $this->assertEquals('A', save_twins(412184)); } } ?>
The $connpdo variable is created in the file database_inc.php
$connpdo = new PDO("mysql:host=$cfgiDbHost;dbname=$cfgiDbDatabase;charset=utf8", $cfgiDbUser, $cfgiDbPasswd);
I have also tried without global but I don’t know what happens. Maybe the use of the namespace?:
use PHPUnitFrameworkTestCase;
I thought that maybe pdo was not enabled but I have checked with php -m
and I see those modules:
PDO pdo_mysql pdo_sqlite pdo_sqlsrv Phar
Advertisement
Answer
Ok, after many months I understood that how PHPunit works. It won’t read that include_once for the database if it’s outside of the method. I moved it inside of the function and also I changed the phpUnit environment for a remote one, on the same server of the database, so the connection is allowed.
After those two changes my test is working: https://www.screencast.com/t/O2ccmcxt2