我有一个测试,我在setup中设置了一些变量:
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
提供程序中引用这些变量。但它们都是NULL。我做错了什么?
数据提供程序在setup()
函数之前运行。您可以在数据提供程序中初始化变量吗?或者,也许把赋值放在构造函数中(并记得调用parent)?
也许使用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],
];
}
}
我在做单元测试时遇到了同样的问题。我认为这与测试的运行方式有关,但我没有对这个主题进行深入研究。我是这样解决的:
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'];
} }
这绝对不是最好的解决方案,但它是有效的:)。
我想你是想重新发明__construct
函数
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],
];
}
}