为了定位缺陷,我们希望把注意力集中于相关的失败测试上。这就是为什么当某个测试所依赖的测试失败时,PHPUnit 会跳过这个测试。利用测试之间的依赖关系可以改进缺陷定位。
DependencyFailureTest.php:
<?php declare(strict_types=1);
use PHPUnit\Framework\TestCase;
final class DependencyFailureTest extends TestCase
{
public function testOne(): void
{
//原型:assertTrue(bool $condition[, string $message = ''])
//当 $condition 为 FALSE 时报告错误,错误讯息由 $message 指定。
$this->assertTrue(false);
}
/**
* @depends testOne
*/
public function testTwo(): void
{
}
}
这里testTwo方法依赖于testOne,但是testOne中有错误的断言。那么运行结果如:
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 --no-configuration C:\Users\Administrator\PhpstormProjects\untitled\DependencyFailureTest.php
PHPUnit 9.5.8 by Sebastian Bergmann and contributors.
FS 2 / 2 (100%)
Time: 00:00.004, Memory: 20.00 MB
There was 1 failure:
1) DependencyFailureTest::testOne
Failed asserting that false is true.
C:\Users\Administrator\PhpstormProjects\untitled\DependencyFailureTest.php:10
FAILURES!
Tests: 2, Assertions: 1, Failures: 1, Skipped: 1.
这里就跳过testOne,并将错误定位到testOne上。并且这里有提示这个testOne上错误的断言详情:Failed asserting that false is true.
那么接下来如果我如果有testThree依赖testTwo,然后testTwo又依赖testOne,此时testOne和testTwo都是错误的断言会如何?
<?php declare(strict_types=1);
use PHPUnit\Framework\TestCase;
final class DependencyFailureTest extends TestCase
{
public function testOne(): void
{
//原型:assertTrue(bool $condition[, string $message = ''])
//当 $condition 为 FALSE 时报告错误,错误讯息由 $message 指定。
$this->assertTrue(false);
}
/**
* @depends testOne
*/
public function testTwo(): void
{
$this->assertTrue(false);
}
/**
* @depends testTwo
*/
public function testThree(): void
{
$this->assertTrue(true);
}
}
那么再次运行结果:
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 --no-configuration C:\Users\Administrator\PhpstormProjects\untitled\DependencyFailureTest.php
PHPUnit 9.5.8 by Sebastian Bergmann and contributors.
FSS 3 / 3 (100%)
Time: 00:00.005, Memory: 20.00 MB
There was 1 failure:
1) DependencyFailureTest::testOne
Failed asserting that false is true.
C:\Users\Administrator\PhpstormProjects\untitled\DependencyFailureTest.php:10
FAILURES!
Tests: 3, Assertions: 1, Failures: 1, Skipped: 2.
会发现它连续跳两个测试,但是定位仍旧定位在testOne上面。