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
Now assume you create new instances of
TestSubjectin your test’s setup method. Because static properties are shared between all instances of a class,TestSubject::iwill 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@backupStaticAttributesannotation.Example:
If you remove the annotation, the third test will fail.