php 在测试之间重置静态方法范围变量

php reset static method-scope variable between tests

我的 php 代码有一大套测试。其中一些代码在函数中使用静态变量来提高性能。但是,在测试期间,这会使 class 处于后续测试的尴尬状态。

有方法ReflectionClass::setStaticPropertyValue()可以在Class范围内重置静态,但是ReflectionMethod只有getStaticVariables,没有setter。

ReflectionMethod 在 php.net 中基本上没有记录,但是 getStaticVariables 返回值的副本,因此更改它对实际的 class 没有影响。 =17=]

我目前包含的代码在 运行 单元测试时基本上不使用静态变量,但这不是一个令人满意的解决方案。有没有办法在方法范围内重置静态变量?有没有办法简单地清除 class 以便重置所有静态信息?

编辑添加:

# Foo.php

class Foo {
    public function bar() {
        static $a = 0;
        $a += 1;
        return $a;
    }
}


# TestFoo.php

class TestFoo extends PHPUnit\Framework\TestCase {
    private $foo;

    setUp() {
        $foo = new Foo();
    }

    test1() {
        $this->assertEquals(1, $foo->bar());
        $this->assertEquals(2, $foo->bar());
    }

    test2() {
        $this->assertEquals(1, $foo->bar());
    }
}

如果 运行 分开,test2 将通过,但即使创建了一个新的 $foo,如果 运行 在 test1.

之后,test2 也会失败

有一种方法会在每次测试后 运行 进行拆卸,因此您可以使用

protected function tearDown()
{
  $this->foo::$a=0;
}

Is there a way to reset a static variable in the method scope?

在方法范围内,是的。如果那是你的意思:

public function bar($b = null) {
    static $a = 0
    $a = $b ?? $a;
    $a += 1;
    return $a;
}

... ->bar($aWillBeSetTo = 0);

Is there a way to simply clear out the class so all statics are reset?

据我所知没有。如果这个静电挡住了你的路,把它撕掉。将其替换为私有实例变量(class的属性),如果需要全局静态,将其设为静态属性 of that class或将其设为全局甚至。适合你的都行。

我所知道的反思中没有任何东西可以修改(只是阅读,你也发现了)。

标准用户区就这么多 PHP。

否则uopz has a function for that: uopz_set_static() — Sets the static variables in function or method scope[DOCS].