企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[TOC] ## 概述 编写代码来将整个场景设置成某个已知的状态,并在测试结束后将其复原到初始状态。这个已知的状态称为测试的 基境(fixture) ## 语法 ``` setUp() // 初始化 - 每个测试函数都会调用的 tearDown() // 执行还原 - 不管是否成功,都会执行 setUpBeforeClass() // 只执行一次 - 如数据库创立连接 tearDownAfterClass() // 只在结束时执行一次 ``` > tearDown() 只有资源数据才需要调用,所以一般是并需要setUp()后,必须调用tearDown() ## 实例 ### hello wold <details> <summary>test.php</summary> ``` <?php use PHPUnit\Framework\TestCase; class LongArrayDiffTest extends TestCase { protected array $stack; public function setUp():void { echo "====start====\n"; $this->stack=[]; } public function tearDown():void { echo "====end====\n"; unset($this->stack); } public static function setUpBeforeClass():void { echo "====setUpBeforeClass====\n"; } public static function tearDownAfterClass():void { echo "====tearDownAfterClass====\n"; } public function testDemo1(){ echo "demo1\n"; $this->stack[]=1; $this->assertEquals([1],$this->stack); } public function testDemo2(){ echo "demo2\n"; $this->stack[]=2; $this->assertEquals([2],$this->stack); } public function testDemo3(){ echo "demo3\n"; $this->stack[]=3; $this->assertEquals([3],$this->stack); } } ``` </details> <br/> 输出 ``` ====setUpBeforeClass==== ====start==== demo1 ====end==== ====start==== demo2 ====end==== ====start==== demo3 ====end==== ====tearDownAfterClass==== ``` ### 基境共享 <details> <summary>test.php</summary> ``` <?php use PHPUnit\Framework\TestCase; class LongArrayDiffTest extends TestCase { /** * @var false|resource */ protected static $handle; public static function setUpBeforeClass(): void{ self::$handle=fopen('1.txt', 'ab'); } public static function tearDownAfterClass(): void{ fclose(self::$handle); } public function testFile(){ $len = fwrite(self::$handle, 'test'); $this->assertEquals(strlen('test'),$len); } } ``` </details> <br/>