gpt4 book ai didi

php - 尝试模拟 PHPUnit 中的依赖项时出现“无法重新声明类”错误

转载 作者:搜寻专家 更新时间:2023-10-31 20:49:22 25 4
gpt4 key购买 nike

我在现有代码库上使用 PHPUnit 实现单元测试。我对单元测试还很陌生,但我知道目标是完全隔离正在测试的代码。这对我的代码库来说很困难,因为许多类都依赖于代码库中的其他类。

依赖项被硬编码到类中,因此无法使用依赖项注入(inject)。我也不想为了测试而重构现有代码。因此,为了将每个类与其依赖项隔离开来,我创建了一个“模拟”类库(不是通过使用 PHPUnit 的模拟框架,而是通过逐字创建一个包含 stub 函数的类库,这些 stub 函数根据特定输入)。

问题是,如果在 phpunit 运行期间,我有一个调用模拟类的测试,然后我尝试测试实际类,我会得到一个 fatal error ,因为 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();
}
}

最佳答案

我认为您需要在隔离的进程中运行测试

要么您为执行测试提供一个参数:“--process-isolation”,要么您设置 $this->processIsolation = true;

关于php - 尝试模拟 PHPUnit 中的依赖项时出现“无法重新声明类”错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9847920/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com