简体   繁体   中英

“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 classes 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM