开发者

"backup and restore operations for static class attributes" in PHP

I saw this phrase in the PHPUnit Documentation:

The implementation of the backup and restore operations for static attributes of classes requires PHP 5.3 (or greater). The implementation of the backup and restore operations for global variables and static attributes of c开发者_如何学JAVAlasses uses serialize() and unserialize()

What is the idea behind this? I mean, I haven't used serialize and unserialize for this purpose. How exactly are these so-called "backup and restore" operations related to static attributes?


The idea is simply to restore the initial known state between tests. Static properties are essentially the same as global variables. Consider

class TestSubject
{
    public static $i = 0;
    public function __construct() { self::$i++; }
}

Now assume you create new instances of TestSubject in your test's setup method. Because static properties are shared between all instances of a class, TestSubject::i will increase each time you create a new instance. It won't be reset. It maintains it's state globally. This is unwanted with Unit-Tests because in order to write reliable tests, you need an isolated, reproducable and known state. Thus, protected members have to be reset between test cases, which you can enable in PHPUnit with the @backupStaticAttributes annotation.

Example:

/**
 * @backupStaticAttributes enabled
 */
class Test extends PHPUnit_Framework_TestCase
{
    public function testInitialValueOfStaticMemberIsZero()
    {
        $this->assertSame(0, TestSubject::$i);
    }
    /**
     * @depends testInitialValueOfStaticMemberIsZero
     */
    public function testCreatingInstancesIncreasesStaticMember()
    {
        new TestSubject();
        new TestSubject();
        new TestSubject();
        $this->assertSame(3, TestSubject::$i);
    }
    /**
     * @depends testCreatingInstancesIncreasesStaticMember
     */
    public function testStaticMembersAreResetBetweenTests()
    {
        $this->assertSame(0, TestSubject::$i);
    }
}

If you remove the annotation, the third test will fail.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜