File tree Expand file tree Collapse file tree 1 file changed +9
-0
lines changed Expand file tree Collapse file tree 1 file changed +9
-0
lines changed Original file line number Diff line number Diff line change @@ -159,6 +159,7 @@ protected function setUp(): void
159
159
### 测试的依赖关系
160
160
有的时候,我们需要测试的两个用例之间可能有依赖关系,比如我们在 TestService 定义如下个方法:
161
161
162
+ ```
162
163
protected $stack = [];
163
164
164
165
public function init()
@@ -175,8 +176,11 @@ public function getStackSize()
175
176
{
176
177
return count($this->stack);
177
178
}
179
+ ```
180
+
178
181
我们在测试 stackContains 方法时,往往要先调用 init 方法,但是在单元测试中,每个方法都有独立的测试用例,如果多次调用有可能会对数据造成污染,那我们能否在 init 方法测试用例的运行基础上运行 stackContains 方法的测试用例呢?这个时候,我们说这两个测试用例之间是具有依赖关系的,PHPUnit 中通过 @depends 注解对这种依赖关系进行了支持,我们可以在 Unit\ExampleTest 中编写测试用例如下:
179
182
183
+ ```
180
184
public function testInitStack()
181
185
{
182
186
$this->service->init();
@@ -194,11 +198,14 @@ public function testStackContains(TestService $service)
194
198
$contains = $service->stackContains('学院君');
195
199
$this->assertTrue($contains);
196
200
}
201
+ ```
202
+
197
203
在 testStackContains 用例中,我们将 testInitStack 用例返回的 $service 实例传递进来,并在此基础上进行测试。
198
204
199
205
### 数据提供器
200
206
除了支持测试用例之间的依赖之外,PHPUnit 还可以通过 @dataProvider 注解为多个测试用例提供初始化数据:
201
207
208
+ ```
202
209
public function initDataProvider()
203
210
{
204
211
return [
@@ -218,6 +225,8 @@ public function testIsStackContains()
218
225
$value = $arguments[0];
219
226
$this->assertTrue($service->stackContains($value));
220
227
}
228
+ ```
229
+
221
230
在这个测试用例中,我们通过 initDataProvider 方法作为数据提供器,数据供给器方法必须声明为 public,其返回值要么是一个数组,其每个元素也是数组;要么是一个实现了 Iterator 接口的对象,在对它进行迭代时每步产生一个数组。每个数组都是测试数据集的一部分,将以它的内容作为参数来调用测试方法。
222
231
223
232
然后我们在需要用到这个数据提供器的测试用例上用 @dataProvider 注解进行声明,在这个示例中我们迭代数据提供器数组,将其中的数据作为参数传入 TestService 的 stackContains 方法以判断对应值在 stack 属性中是否存在。
You can’t perform that action at this time.
0 commit comments