PHPUnit是否自动重置类变量?Magento2集成测试类型错误排查
Magento 2集成测试中int类型属性赋值null的问题排查
测试代码(Magento 2集成测试环境)
class GenerateTest extends AbstractTestCase { private int $requestTime = 0; ... protected function setUp(): void { $this->requestTime = $_SERVER['REQUEST_TIME']; // 已通过var_dump()验证不为null parent::setUp(); } protected function tearDown(): void { parent::tearDown(); $_SERVER['REQUEST_TIME'] = $this->requestTime; } }
出现的错误
Cannot assign null to property GenerateTest::$requestTime of type int
异常细节
- 错误无具体行号提示
- 即使注释掉
setUp和tearDown中所有与$requestTime相关的代码,错误仍然出现 - 类内没有其他任何对
$requestTime的赋值操作 - 将属性类型声明改为
?int(可空int)后,问题消失,但希望明确根因,同时确认:PHPUnit是否会自动重置类变量?
补充测试
编写了简化版PHPUnit测试用例,无法复现该问题:
<?php declare(strict_types=1); class Test extends \PHPUnit\Framework\TestCase { private int $requestTime = 0; protected function setUp(): void { $this->requestTime = $_SERVER['REQUEST_TIME']; // 已通过var_dump()验证不为null parent::setUp(); } protected function tearDown(): void { parent::tearDown(); $_SERVER['REQUEST_TIME'] = $this->requestTime; } public function testFoo() { } }
问题仅在Magento 2集成测试场景下出现,需要进一步排查。
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

