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

256

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?

656

Answer

Solution:

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 ofTestSubject 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.

People are also looking for solutions to the problem: PHP MySQL dont get last selected

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.