您当前的位置: 首页 > 慢生活 > 程序人生 网站首页程序人生
phpunit数据供给器
发布时间:2021-09-12 23:04:20编辑:雪饮阅读()
Phpunit中数据供给器是一种用于提供给一个测试方法数据的。
那个这个测试方法要声明依赖一个数据供给器,可用关键字dataProvider。
测试方法可以接受任意参数。这些参数由一个或多个数据供给器方法提供。
数据供给器方法必须声明为 public,其返回值要么是一个数组,其每个元素也是数组;要么是一个实现了 Iterator 接口的对象,在对它进行迭代时每步产生一个数组。每个数组都是测试数据集的一部分,将以它的内容作为参数来调用测试方法。
那么这里主要只提供普通的数组的实例:
DataTest.php:
<?php declare(strict_types=1);
use PHPUnit\Framework\TestCase;
final class DataTest extends TestCase
{
/**
* @dataProvider additionProvider
*/
public function testAdd(int $a, int $b, int $expected): void
{
$this->assertSame($expected, $a + $b);
}
public function additionProvider(): array
{
return [
[0, 0, 0],
[0, 1, 1],
[1, 0, 1],
[1, 1, 3]
];
}
}
use PHPUnit\Framework\TestCase;
final class DataTest extends TestCase
{
/**
* @dataProvider additionProvider
*/
public function testAdd(int $a, int $b, int $expected): void
{
$this->assertSame($expected, $a + $b);
}
public function additionProvider(): array
{
return [
[0, 0, 0],
[0, 1, 1],
[1, 0, 1],
[1, 1, 3]
];
}
}
这里定义了testAdd测试方法,其接收$a和$b以及$expected参数。
$a和$b、$expected分别对应接收数据提供器中每个元素的0下标,1小标,2下标。(我猜想这里测试方法若是四个参数,那么数据提供器的每个元素中也应该是拥有4个元素的子数组)。
那么这里testAdd测试方法断言数据提供器中每个元素中的0下标与1下标对应的值之和的数据类型及值本身与2下标对应值的数据类型和值本身都是相同的。
那么很显然这里断言会在数据供给器中最后一组数据的时候断言失败:
C:\Users\Administrator>D:\phpstudy_pro\Extensions\php\php7.3.4nts\php.exe D:\phpstudy_pro\Extensions\php\php7.3.4nts\phpunit-9.5.8.phar C:\Users\Administrator\PhpstormProjects\untitled\DataTest.php
PHPUnit 9.5.8 by Sebastian Bergmann and contributors.
...F 4 / 4 (100%)
Time: 00:00.006, Memory: 20.00 MB
There was 1 failure:
1) DataTest::testAdd with data set #3 (1, 1, 3)
Failed asserting that 2 is identical to 3.
C:\Users\Administrator\PhpstormProjects\untitled\DataTest.php:11
FAILURES!
Tests: 4, Assertions: 4, Failures: 1.
关键字词:phpunit,数据供给器