【发布时间】:2011-03-09 12:17:12
【问题描述】:
我在用 PHPUnit 模拟 PDO 对象时遇到了困难。
网络上似乎没有太多关于我的问题的信息,但我可以收集到的信息:
- PDO 具有“最终”__wakeup 和 __sleep 防止它被序列化的方法。
- PHPunit 的模拟对象实现会在某些时候序列化对象。
- 发生这种情况时,单元测试会因 PDO 生成的 PHP 错误而失败。
通过在单元测试中添加以下行来防止这种行为:
class MyTest extends PHPUnit_Framework_TestCase
{
protected $backupGlobals = FALSE;
// ...
}
来源:http://sebastian-bergmann.de/archives/797-Global-Variables-and-PHPUnit.html
这对我不起作用,我的测试仍然产生错误。
完整的测试代码:
class MyTest extends PHPUnit_Framework_TestCase
{
/**
* @var MyTest
*/
private $MyTestr;
protected $backupGlobals = FALSE;
/**
* Prepares the environment before running a test.
*/
protected function setUp()
{
parent::setUp();
}
/**
* Cleans up the environment after running a test.
*/
protected function tearDown()
{
parent::tearDown();
}
public function __construct()
{
$this->backupGlobals = false;
parent::__construct();
}
/**
* Tests MyTest->__construct()
*/
public function test__construct()
{
$pdoMock = $this->getMock('PDO', array('prepare'), array(), '', false);
$classToTest = new MyTest($pdoMock);
// Assert stuff here!
}
// More test code.......
任何 PHPUnit 专业人士帮我一把?
谢谢,
本
【问题讨论】:
-
有趣的是人们如何调试他们的代码。我更喜欢直接调试代码并将所有这些单元测试垃圾扔进垃圾箱。我把它留给需要自动化测试的大人物,因为他们的应用程序太大了,它可能会在无人火星任务中自行起飞。
标签: php unit-testing pdo phpunit