使用PHPUnit类'mysqli'找不到

时间:2012-04-17 13:06:50

标签: php mysqli phpunit

我刚开始PHPUnit。我写的一些简单测试正在进行中。所以一般来说PHPUnit已启动并正在运行。但是MySQLi类有问题。

在我的代码中,它工作正常。这是行:

$this->mysqli = new \mysqli($this->host, $user->getUser(), $user->getPwd(), $this->db);

当运行phpunit解析此行时,我收到以下错误消息(指向该行):

PHP Fatal error:  Class 'mysqli' not found in /opt/lampp/htdocs/...

两种可能性(我认为):

1)我缺少一些功能/扩展/配置步骤/与使用MySQLi扩展的PHPUnit正确设置相关的其他内容。

修改

如果我测试扩展程序extension_loaded('mysqli'),则会在我的正常代码中返回true。如果我在测试中执行以下操作,则会跳过测试(即返回false):

if (!extension_loaded('mysqli')) {
    $this->markTestSkipped(
        'The MySQLi extension is not available.'
    );
}

/修改

2)我的代码可能有问题。我正在尝试模拟User对象以进行测试连接。所以这就是:

<?php
class ConnectionTest extends \PHPUnit_Framework_TestCase
{
    private $connection;

    protected function setUp()
    {
        $user = $this->getMockBuilder('mysqli\User')
                     ->setMethods(array('getUser', 'getPwd'))
                     ->getMock();
        $user->expects($this->once())
             ->method('getUser')
             ->will($this->returnValue('username'));
        $user->expects($this->once())
             ->method('getPwd')
             ->will($this->returnValue('p@ssw0rd'));

        $this->connection = new \mysqli\Connection($user);
    }

    public function testInternalTypeGetMysqli()
    {
        $actual   = $this->connection->getMysqli();
        $expected = 'resource';

        $this->assertInternalType($expected, $actual);
    }

    protected function tearDown()
    {
        unset($this->connection);
    }
}

经过测试的Connection类看起来像这样:

<?php
namespace mysqli;

class Connection
{
    protected $mysqli;
    protected $host = 'localhost';
    protected $db   = 'database';

    public function __construct(\mysqli\User $user)
    {
        $this->mysqli = new \mysqli($this->host, 
                                    $user->getUser(),
                                    $user->getPwd(),
                                    $this->db);
        if (mysqli_connect_errno()) {
            throw new \RuntimeException(mysqli_connect_error());
        }
    }

    public function getMysqli()
    {
        return $this->mysqli;
    }
}

这整件事是安装问题。我正在使用提供PHP的XAMPP安装。独立安装 PHPUnit 使其使用不同的设置!所以在我的浏览器(XAMPP驱动)一切都很好,但在我的命令行中,MySQLi扩展已经一共丢失了! Debian提供了一个名为 php5-mysqlnd 的软件包。安装好这一切都很好! (除了出现的其他错误: - )

1 个答案:

答案 0 :(得分:5)

PHPUnit通常在CLI - 命令行界面中运行。

你所拥有的PHP与网络服务器不同。不同的二进制文件,通常也有不同的配置。

$ php -r "new mysqli();"

应该给你同样的错误。验证二进制文件和配置的位置:

$ which php

$ php -i | grep ini

确保您已安装并启用the extension for the mysqli class。配置完成后,您应该能够完美地运行单元测试。

相关问题