我有这个代码:
public function testFoo() {
$this->object = newBar();
}
但稍后,例如,在方法 testAdd()
中,$this->object
为 null
。 testAdd
在 testFoo
之后执行。
为什么会出现这种情况,整个测试用例是否有类似 setUp 的方法?
最佳答案
每个测试方法都在测试用例类的新实例上执行。确实有一个在每次测试之前调用的设置方法,它被称为 setUp
.
public function setUp() {
$this->object = newBar();
}
public function testFoo() {
// use $this->object here
}
public function testBar() {
// use $this->object here too, though it's a *different* instance of newBar
}
如果您需要在测试用例的所有测试之间共享状态——通常是不明智的——您可以使用静态 setUpBeforeClass
方法。
public static function setUpBeforeClass() {
self::$object = newBar();
}
public function testFoo() {
// use self::$object here
}
public function testBar() {
// use self::$object here too, same instance as above
}
关于php - 如何访问在另一个 PHPUnit 测试中初始化的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11441979/