Php can';t在数据提供程序中引用“$this”
我进行了一项测试,在设置中设置了一些变量:Php can';t在数据提供程序中引用“$this”,php,phpunit,Php,Phpunit,我进行了一项测试,在设置中设置了一些变量: class MyTest extends PHPUnit_Framework_TestCase { private $foo; private $bar; function setUp() { $this->foo = "hello"; $this->bar = "there"; } private function provideStuff() { ret
class MyTest extends PHPUnit_Framework_TestCase {
private $foo;
private $bar;
function setUp() {
$this->foo = "hello";
$this->bar = "there";
}
private function provideStuff() {
return [
["hello", $this->foo],
["there", $this->bar],
];
}
}
然后我引用
provideStuff
提供程序中的那些变量。但它们都是空的。我做错了什么?数据提供程序在setup()
函数之前运行。您可以在数据提供程序中初始化变量吗?或者,也可以将赋值放在构造函数中(记住调用parent)我认为您正在尝试重新创建\uu构造函数
函数
class MyTest extends PHPUnit_Framework_TestCase {
private $foo;
private $bar;
function __construct() {
$this->foo = "hello";
$this->bar = "there";
}
private function provideStuff() {
return [
["hello", $this->foo],
["there", $this->bar],
];
}
}
我在做单元测试时遇到了同样的问题。我认为这与测试的运行方式有关,但我没有对此进行深入研究。我是这样解决的:
class MyTest extends PHPUnit_Framework_TestCase {
function setUp() {
$data['foo'] = "hello";
$data['bar'] = "there";
return $data;
}
/**
* @param array $data
* @depends setUp
*/
private function provideStuff($data) {
echo $data['foo'];
} }
这显然不是最好的解决方案,但它确实有效:)。也许使用
setUpBeforeClass
和静态变量可以解决您的问题
class MyTest extends PHPUnit_Framework_TestCase {
private static $foo;
private static $bar;
public static function setUpBeforeClass() {
self::$foo = "hello";
self::$bar = "there";
}
private function provideStuff() {
return [
["hello", self::$foo],
["there", self::$bar],
];
}
}
它没有回答问题。如果他的目标是在类创建时分配这些变量,这是通过
setUp()
函数假定的,我看不出为什么不这样做。setUp
和tearDown
围绕每个测试方法调用,而不仅仅是在对象构造上。如果这样做,您仍然需要调用parent::\uu construct()
@VladtheImpala True。我会更新我的编辑,但这似乎不是作者想要完成的;)看起来这不会在提供程序之前运行,因为self::$foo等都为NULL。这可能会起作用……我不习惯在这里重写构造函数。对于未来的访问者:调用父级构造函数也很重要,否则您将遇到此问题,因此setUp
的结果将传递给提供者?刚刚测试过这个,看起来没有。