gpt4 book ai didi

php - 如何访问在另一个 PHPUnit 测试中初始化的对象

转载 作者:搜寻专家 更新时间:2023-10-31 20:47:47 24 4
gpt4 key购买 nike

我有这个代码:

public function testFoo() {
$this->object = newBar();
}

但稍后,例如,在方法 testAdd() 中,$this->objectnulltestAddtestFoo 之后执行。

为什么会出现这种情况,整个测试用例是否有类似 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com