我刚从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扩展的正确设置相关的其他功能
/扩展/配置步骤。编辑
如果我测试扩展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);
}
}
测试的连接类如下所示:
<?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 的软件包。安装好这个都可以正常工作!(除了出现其他错误:-)
PHPUnit 通常在 CLI - 命令行界面中运行。
你在那里得到的PHP与Web服务器不同。不同的二进制文件,通常也有不同的配置。
$ php -r "new mysqli();"
应该给你同样的错误。验证二进制文件和配置的位置:
$ which php
和
$ php -i | grep ini
确保已安装并启用了 mysqli
类的扩展。配置完成后,您应该能够完美地运行单元测试。