mysqli_query():在PHPUnit中测试PHP函数时无法获取mysqli

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mysqli_query():在PHPUnit中测试PHP函数时无法获取mysqli相关的知识,希望对你有一定的参考价值。

我正在尝试在我正在研究的学校项目上编写一个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:Xampphtdocsmusicstore-oop-beta	est>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:Xampphtdocsmusicstore-oop-betaappDatabase.php:38
C:Xampphtdocsmusicstore-oop-betaappDatabaseHelper.php:23
C:Xampphtdocsmusicstore-oop-betaappDatabaseHelper.php:37
C:Xampphtdocsmusicstore-oop-beta	estMusicStoreTest.php:62

There were 2 skipped tests:

1) MusicStoreTest::testAddArtist
Artist Add Test Skipped

C:Xampphtdocsmusicstore-oop-beta	estMusicStoreTest.php:24

2) MusicStoreTest::testAddAlbum
Album Add Test Skipped

C:Xampphtdocsmusicstore-oop-beta	estMusicStoreTest.php:40

FAILURES!
Tests: 3, Assertions: 0, Errors: 1, Skipped: 2.
答案

当数据库变量(在您的情况下为$ 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变量的不同变量。

以上是关于mysqli_query():在PHPUnit中测试PHP函数时无法获取mysqli的主要内容,如果未能解决你的问题,请参考以下文章

如何在 PHP 中使用 mysqli_query()?

警告:mysqli_query() 期望参数 2 是字符串,对象在

让 mysqli_query 执行的问题

mysqli_query():MySQL服务器已消失[重复]

如何在 PHP 的 mysqli_query() 中转义双引号字符?

mysqli_query(“set nams utf8”)为FALSE