PHPUnit 4.8模拟mysql数据库接口

时间:2017-11-07 18:23:14

标签: php mysql unit-testing phpunit

下午好,

我有一堆遗留代码使用旧的mysql库(例如mysql_query($sql))并尝试使用PHPUnit进行测试(4.8是将在服务器上运行的最新版本原因)。

是否有人知道如何模拟此数据库连接,以便在运行预定查询时它可以返回预定的结果?我尝试过使用getConnection()(根据这里的文档:http://devdocs.io/phpunit~4/database)无济于事。

例如我有这个课程:

class Raffle {
    ...
    public static function loadAll($filter=""){
        //$filter = mysql_real_escape_string($filter); // protect against SQL injection
        $raffles = []; // the array to return

        $sql = "SELECT * FROM raffles $filter;"; // include the user filter in the query
        $query = mysql_query($sql);

        //echo mysql_error();

        while($row = mysql_fetch_assoc($query)){
            $raffles[] = Raffle::loadFromRow($row); // generate the raffe instance and add it to the array
        }
        return $raffles; // return the array
    }
    ...
}

mysql_connect()调用在名为db.php的文件中完成,该文件在需要的每个页面上加载,而不是在类文件本身中加载。)

提前致谢。

1 个答案:

答案 0 :(得分:0)

对于遇到这种情况的其他人,我发现为PDO构建一个包含函数api回退的模拟允许我将代码迁移到基于Testable OO的模型,同时仍然使用旧的mysql库引擎盖。

例如:

// the basic interfaces (function names taken from PDO
interface DBConnAdapter {
    public function query($sql);
}
// since PDO splits connections and statements the adapter should do the same
interface DBQueryAdapter {
    public function num_rows();
    public function fetch_assoc();
}
...
class DBAdapter implements DBConnAdapter {

    public function query($sql){
        $query = mysql_query($sql); // run the query using the legacy api
        return $query ? new QueryAdapter($query) : false; // return a new query adapter or false.
    }

}
...
// an example of a basic mock object to test sql queries being sent to the server (inspired by mockjax :-) ) 
class DBMock implements DBConnAdapter {

    public $queries = []; // array of queries already executed
    public $results = []; // array of precomputed results. (key is SQL and value is the returned result (nested array))

    public function query($sql) {
        if($this->results[$sql]){
            $query = new DBQueryMock($sql, $this->results[$sql]); // a mock of PDOStatement that takes the sql it ran and the results to return
            $queries[] = $query; // add the query to the array
            return $query; // return the query
        }
        return false; // we do not know the statement so lets pretend it failed
    }
    // add a result to the list
    public function add_single_result($sql, $result){
        // check if the index was set, if not make an array there
        if(!isset($this->results[$sql])) $this->results[$sql] = [];
        // add the result to the end of the array
        $this->results[$sql][] = $result; 
        // return its index
        return count($this->results[$sql]) - 1;
    }
}

不可否认,这不是一个理想的解决方案,因为它需要修改代码以支持适配器对象并删除某些功能(例如mysql_real_escape_string),但它有效....

如果您有更好的解决方案,请分享:-)谢谢!