企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[TOC] ## 概述 数据供给器,可以抽象出数据与测试的,便于管理 - 测试方法可以接受任意参数。这些参数由数据供给器方法,用`@dataProvider`提供 - 数据供给器方法必须声明为 public,其返回值要么是一个数组,其每个元素也是数组,要么是一个实现了 Iterator 接口的对象 ## 实例 ### 测试数据为数组 <details> <summary>test.php</summary> ``` <?php use PHPUnit\Framework\TestCase; class DataTest extends TestCase{ /** * @dataProvider additionProvider * @param $a * @param $b * @param $expected */ public function testAdd($a,$b,$expected){ $this->assertEquals($expected,$a+$b); } /** * @return int[][] */ public function additionProvider(){ // 字符串key 为注释,可以不设置 return [ 'adding zeros' => [0, 0, 0], 'zero plus one' => [0, 1, 1], 'one plus zero' => [1, 0, 1], 'one plus one' => [1, 1, 2] ]; } } ``` </details> <br/> ### 测试数据为可迭代对象 <details> <summary>test.php</summary> ``` <?php use PHPUnit\Framework\TestCase; class IteratorDemo implements Iterator{ private array $data = [ [0, 0, 0], [0, 1, 1], [1, 0, 1], [1, 1, 2] ]; private int $index = 0; public function current(){ return $this->data[$this->index]; } public function next(){ $this->index++; } public function key(){ return "key is :".$this->index; } public function valid(){ return $this->index<=count($this->data)-1; } public function rewind(){ $this->index=0; } } class DataTest extends TestCase{ /** * @dataProvider additionProvider * @param $a * @param $b * @param $expected */ public function testAdd($a,$b,$expected){ $this->assertEquals($expected,$a+$b); } /** * @return Iterator */ public function additionProvider(){ // 字符串key 为注释,可以不设置 return new IteratorDemo(); } } ``` </details> <br/>