我刚开始使用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) 我缺少一些功能/扩展/配置步骤/与正确设置 PHPUnit 与 MySQLi 扩展一起使用的其他内容。
编辑
如果我测试扩展名extension_loaded('mysqli')
,它会true
在我的正常代码中返回。如果我在测试中执行以下操作,它将跳过测试(即它返回false
):
if (!extension_loaded('mysqli')) {
$this->markTestSkipped(
'The MySQLi extension is not available.'
);
}
/编辑
2)我的代码可能有问题。我正在尝试模拟用户对象以建立测试连接。所以这里是:
<?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的软件包。安装后一切正常!(出现的其他错误除外:-)