PHPUnit存储测试类的属性

mck*_*k89 15 php testing phpunit properties

我是PHPUnit的初学者.

这是我创建的示例测试类:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

执行testSecond时,会抛出错误" Undefined property NewTest::$foo".

为什么会这样?每次测试执行后,PHPUnit都会清除新属性吗?有没有办法在测试中设置属性,以便在同一测试类的其他测试中可以访问它?

Gor*_*don 24

您正在testFirst()方法内设置foo属性.PHPUnit将在测试之间重置环境/为每个测试方法创建一个新的"NewTest"实例(如果他们没有@depends注释),所以如果你想foo设置为true必须在依赖测试中重新创建该状态或使用该setup()方法.

随着setup()(docs):

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

随着@depends(docs):

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

以上所有都应该通过.

EDIT 必须删除@backupGlobals解决方案.这是完全错的.