一、默认情况下,PHPUnit将测试在执行中触发的PHP错误、警告、通知都转换为异常,所以在这样的情况下,单元测试就会终止。当程序不能保证没有Notice时,又想单元测试可以顺利执行的话,可以修改配置文件phpunit.xml
<phpunit backupGlobals="true" backupStaticAttributes="false" cacheTokens="false" colors="false" convertErrorsToExceptions="true" convertNoticesToExceptions="true" convertWarningsToExceptions="true" forceCoversAnnotation="false" mapTestClassNameToCoveredClassName="false" printerClass="PHPUnit_TextUI_ResultPrinter" processIsolation="false" stopOnError="false" stopOnFailure="false" stopOnIncomplete="false" stopOnSkipped="false" testSuiteLoaderClass="PHPUnit_Runner_StandardTestSuiteLoader" timeoutForSmallTests="1" timeoutForMediumTests="10" timeoutForLargeTests="60" strict="false" verbose="false"> </phpunit>
将convertNoticesToExceptions设为false可以禁用此功能,还有convertWarningsToExceptions
这些选项都是在命令行选项里无法修改的,当执行的时候可以使用phpunit-cphpunit.xml来指定配置选项。
二、
对PHP错误进行测试
<?php class ExpectedErrorTest extends PHPUnit_Framework_TestCase { /** * @expectedException PHPUnit_Framework_Error */ public function testFailingInclude() { include 'not_existing_file.php'; } } ?>
执行结果
phpunit -d error_reporting=2 ExpectedErrorTest PHPUnit 3.8.0 by Sebastian Bergmann. . Time: 0 seconds, Memory: 5.25Mb OK (1 test, 1 assertion)
注意
PHP的error_reporting运行时配置会对PHPUnit将哪些错误转换为异常有所限制。如果在这个特性上碰到问题,请确认PHP的配置中没有抑制想要测试的错误类型。
三、对异常进行测试
<?php class ExceptionTest extends PHPUnit_Framework_TestCase { public function testException() { try { // ... 预期会引发异常的代码 ... } catch (InvalidArgumentException $expected) { return; } $this->fail('预期的异常未出现。'); } } ?>
当预期会引发异常的代码并没有引发异常时,后面对fail()的调用将会中止测试,并通告测试有问题。如果预期的异常出现了,将执行catch代码块,测试将会成功结束。