上篇了解了”在同一个测试中组合 @depends 和 @dataProvider”
那么如果是同一个测试使用多个数据供给器呢?
DataTest.php:
<?php declare(strict_types=1);
use PHPUnit\Framework\TestCase;
final class DataTest extends TestCase
{
/**
* @dataProvider additionWithNonNegativeNumbersProvider
* @dataProvider additionWithNegativeNumbersProvider
*/
public function testAdd(int $a, int $b, int $expected): void
{
print_r(func_get_args());
echo "\r\n";
$this->assertSame($expected, $a + $b);
}
public function additionWithNonNegativeNumbersProvider(): array
{
return [
[0, 1, 1],
[1, 0, 1],
[1, 1, 3]
];
}
public function additionWithNegativeNumbersProvider(): array
{
return [
[-1, 1, 0],
[-1, -1, -2],
[1, -1, 0]
];
}
}
运行效果如:
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.
.Array
(
[0] => 0
[1] => 1
[2] => 1
)
.Array
(
[0] => 1
[1] => 0
[2] => 1
)
FArray
(
[0] => 1
[1] => 1
[2] => 3
)
.Array
(
[0] => -1
[1] => 1
[2] => 0
)
.Array
(
[0] => -1
[1] => -1
[2] => -2
)
. 6 / 6 (100%)Array
(
[0] => 1
[1] => -1
[2] => 0
)
Time: 00:00.010, Memory: 20.00 MB
There was 1 failure:
1) DataTest::testAdd with data set #2 (1, 1, 3)
Failed asserting that 2 is identical to 3.
C:\Users\Administrator\PhpstormProjects\untitled\DataTest.php:14
FAILURES!
Tests: 6, Assertions: 6, Failures: 1.
可以看到这多个数据供给器就相当于多组数据,则使用多组数据的这个测试方法则会按dataProvider定义的语法顺序进行顺序的遍历每组数据进行测试。
那么为了证明确实是按顺序的,我们可以将这里dataProvider定义的顺序调整下。
/**
* @dataProvider additionWithNegativeNumbersProvider
* @dataProvider additionWithNonNegativeNumbersProvider
*/
public function testAdd(int $a, int $b, int $expected): void
{
print_r(func_get_args());
echo "\r\n";
$this->assertSame($expected, $a + $b);
}
调整成这样后,我们再次运行:
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.
.Array
(
[0] => -1
[1] => 1
[2] => 0
)
.Array
(
[0] => -1
[1] => -1
[2] => -2
)
.Array
(
[0] => 1
[1] => -1
[2] => 0
)
.Array
(
[0] => 0
[1] => 1
[2] => 1
)
.Array
(
[0] => 1
[1] => 0
[2] => 1
)
F 6 / 6 (100%)Array
(
[0] => 1
[1] => 1
[2] => 3
)
Time: 00:00.006, Memory: 20.00 MB
There was 1 failure:
1) DataTest::testAdd with data set #5 (1, 1, 3)
Failed asserting that 2 is identical to 3.
C:\Users\Administrator\PhpstormProjects\untitled\DataTest.php:14
FAILURES!
Tests: 6, Assertions: 6, Failures: 1.
可以看到这次是先运行有负数的这组数据了