【发布时间】:2012-04-08 12:40:00
【问题描述】:
我正在现有代码库上使用 PHPUnit 实施单元测试。我对单元测试相当陌生,但我知道目标是完全隔离正在测试的代码。这对我的代码库来说很困难,因为许多类都依赖于代码库中的其他类。
依赖项被硬编码到类中,因此无法使用依赖项注入。我也不想仅仅为了测试而重构现有代码。 因此,为了将每个类与其依赖项隔离开来,我创建了一个“模拟”类库(不是通过使用 PHPUnit 的模拟框架,而是通过创建一个包含存根函数的类库,这些存根函数根据特定的返回值输入)。
问题是,如果在运行 phpunit 期间,我有一个调用模拟类的测试,然后我尝试测试实际类,我会收到一个致命错误,因为 PHP 认为这是重新声明类。这是我的意思的简化示例。请注意,即使我取消设置已包含的类的所有实例并在 tearDown 方法中清除包含路径,这仍然会失败。同样,我是单元测试的新手,所以如果我以错误的方式处理这个问题或遗漏了一些明显的东西,请告诉我。
一个更大的问题可能是这种方法是否会朝着隔离代码的方向发展,以及使用真实对象作为我的类的依赖项是否真的有好处。
#### real A
require_once 'b.class.php';
class A {
private $b;
public function __construct() {
$this->b = new B();
}
public function myMethod($foo) {
return $this->b->exampleMethod($foo);
}
}
#### real B
class B {
public function exampleMethod($foo) {
return $foo . "bar";
}
}
#### mock B
class B {
public function exampleMethod($foo) {
switch($foo) {
case 'test':
return 'testbar';
default:
throw new Exception('Unexpected input for stub function ' . __FUNCTION__);
}
}
}
#### test A
class TestA extends PHPUnit_Extensions_Database_TestCase {
protected function setUp()
{
// include mocks specific to this test
set_include_path(get_include_path() . PATH_SEPARATOR . 'tests/A/mocks');
// require the class we are testing
require_once 'a.class.php';
$this->a = new A();
}
public function testMyMethod() {
$this->assertEquals('testbar', $a->myMethod('test'));
}
}
#### test B
class TestB extends PHPUnit_Extensions_Database_TestCase {
protected function setUp()
{
// include mocks specific to this test
set_include_path(get_include_path() . PATH_SEPARATOR . 'tests/B/mocks');
// require the class we are testing
// THIS FAILS WITH: 'PHP Fatal error: Cannot redeclare class B'
require_once 'b.class.php';
$this->b = new AB();
}
}
【问题讨论】:
标签: php unit-testing testing mocking phpunit