PHPUnit在测试类上存储属性
我是PHPUnit的初学者 这是我创建的一个示例测试类:PHPUnit在测试类上存储属性,php,testing,properties,phpunit,Php,Testing,Properties,Phpunit,我是PHPUnit的初学者 这是我创建的一个示例测试类: class NewTest extends PHPUnit_Framework_TestCase { protected $foo; function testFirst () { $this->foo = true; $this->assertTrue($this->foo); } /** * @depends testFirst
class NewTest extends PHPUnit_Framework_TestCase
{
protected $foo;
function testFirst ()
{
$this->foo = true;
$this->assertTrue($this->foo);
}
/**
* @depends testFirst
*/
function testSecond ()
{
$this->assertTrue($this->foo);
}
}
执行testSecond时,它会抛出一个错误,提示“未定义的属性NewTest::$foo
”
为什么会发生这种情况?每次测试执行后PHPUnit是否清除新属性?有没有办法在测试中设置属性,以便在同一测试类的其他测试中可以访问该属性?- 你可以使用
- 您可以初始化方法中的某些内容
通常,您希望避免一个测试影响另一个测试。这确保了测试是干净的并且总是有效的,而不是在test1创建的某些边缘情况下。您正在
testFirst()
方法中设置foo属性。PHPUnit将在测试之间重置环境/为每个测试方法创建一个新的“NewTest”实例(如果它们没有@dependens注释),因此如果要将foo
设置为true
,则必须在依赖测试中重新创建该状态或使用setup()
方法
使用setup()
():
与@相关的
():
所有这些都应该通过
EDIT必须删除@backupGlobals解决方案。这显然是错误的
class NewTest extends PHPUnit_Framework_TestCase
{
protected $foo;
protected function setup()
{
$this->foo = TRUE;
}
function testFirst ()
{
$this->assertTrue($this->foo);
}
/**
* @depends testFirst
*/
function testSecond ()
{
$this->assertTrue($this->foo);
}
}
class NewTest extends PHPUnit_Framework_TestCase
{
protected $foo;
function testFirst ()
{
$this->foo = TRUE;
$this->assertTrue($this->foo);
return $this->foo;
}
/**
* @depends testFirst
*/
function testSecond($foo)
{
$this->foo = $foo;
$this->assertTrue($this->foo);
}
}