我试图在我正在研究的学校项目上编写一个PHPUnit测试函数。这些功能适用于普通网站。但是当我尝试使用PHPUnit测试数据库相关的操作时,我不断获得mysqli_query(): Couldn't fetch mysqli
。
以下是示例代码段:
PHPUnit文件:test.php
function testFindById() {
$expected_object = "Artist";
$result = Artist::find_by_id($id);
$result_type = gettype($result);
$this->assertEquals($expected_object, $result_type);
}
DatabaseHelper类:DatabaseHelper.php
public static function find_by_sql($sql) {
global $database;
$result = $database->query($sql);
$objects = array();
if ($result) {
while ($row = mysqli_fetch_array($result)) {
$objects[] = static::new_instance($row);
}
}
return $objects;
}
public static function find_by_id($id) {
global $database;
$sql = "SELECT * FROM " . static::$table_name . " WHERE id = $id LIMIT 1";
$result = static::find_by_sql($sql);
if (!empty($result)) {
return array_shift($result);
} else {
return false;
}
}
艺术家类:Artist.php
class Artist extends DatabaseHelper {
protected static table_name = "artists";
// more irrelevant code follows
}
测试输出
C:\Xampp\htdocs\musicstore-oop-beta\test>phpunit --verbose MusicStoreTest.php
PHPUnit 3.7.21 by Sebastian Bergmann.
SSE
Time: 0 seconds, Memory: 2.00Mb
There was 1 error:
1) MusicStoreTest::testFindById
mysqli_query(): Couldn't fetch mysqli
C:\Xampp\htdocs\musicstore-oop-beta\app\Database.php:38
C:\Xampp\htdocs\musicstore-oop-beta\app\DatabaseHelper.php:23
C:\Xampp\htdocs\musicstore-oop-beta\app\DatabaseHelper.php:37
C:\Xampp\htdocs\musicstore-oop-beta\test\MusicStoreTest.php:62
There were 2 skipped tests:
1) MusicStoreTest::testAddArtist
Artist Add Test Skipped
C:\Xampp\htdocs\musicstore-oop-beta\test\MusicStoreTest.php:24
2) MusicStoreTest::testAddAlbum
Album Add Test Skipped
C:\Xampp\htdocs\musicstore-oop-beta\test\MusicStoreTest.php:40
FAILURES!
Tests: 3, Assertions: 0, Errors: 1, Skipped: 2.
答案 0 :(得分:-1)
当数据库变量(在您的情况下为$ database)未引用连接的数据库时,会发生这种情况。您应该检查数据库连接是否有效:
$database = new mysqli('db_host','user','password','db_name');
if ($database->connect_errno) {
error_log("Errno: " . $mysqli->connect_errno . ':' . mysqli->connect_error);
}
如果用于存储数据库对象的变量不在范围内,也会发生这种情况。假设缺少global $database;
语句(不适用于具有该语句的代码),则$database
只有本地函数范围 - 它将是全局$database
变量的不同变量。