您当前的位置: 首页 > 慢生活 > 程序人生 网站首页程序人生
phpunit对会引发PHP 错误的代码的返回值进行测试
发布时间:2021-09-13 22:52:05编辑:雪饮阅读()
有时候需要测试下php代码中某个函数的执行结果,但是若这个函数中有错误发生(php级别的错误,会直接报错的那种),则会导致断言不能正常执行,那么这种情况下一般的这个函数的执行结果可以认定为false的。但是由于函数内部出现了错误,则断言也就不能正常执行。可以通关@来抑制错误同时可以拿到返回值。
ErrorSuppressionTest.php:
<?php declare(strict_types=1);
use PHPUnit\Framework\TestCase;
final class ErrorSuppressionTest extends TestCase
{
public function testFileWriting(): void
{
$writer = new FileWriter;
$this->assertFalse(@$writer->write('/is-not-writeable/file', 'stuff'));
}
}
final class FileWriter
{
public function write($file, $content)
{
$file = fopen($file, 'w');
if ($file === false) {
return false;
}
// ...
}
}
use PHPUnit\Framework\TestCase;
final class ErrorSuppressionTest extends TestCase
{
public function testFileWriting(): void
{
$writer = new FileWriter;
$this->assertFalse(@$writer->write('/is-not-writeable/file', 'stuff'));
}
}
final class FileWriter
{
public function write($file, $content)
{
$file = fopen($file, 'w');
if ($file === false) {
return false;
}
// ...
}
}
测试执行结果如:
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\ErrorSuppressionTest.php
PHPUnit 9.5.8 by Sebastian Bergmann and contributors.
. 1 / 1 (100%)
Time: 00:00.005, Memory: 20.00 MB
OK (1 test, 1 assertion)
那么如果我去除这个@然后再次测试运行结果就出现了错误了:
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\ErrorSuppressionTest.php
PHPUnit 9.5.8 by Sebastian Bergmann and contributors.
E 1 / 1 (100%)
Time: 00:00.004, Memory: 20.00 MB
There was 1 error:
1) ErrorSuppressionTest::testFileWriting
fopen(/is-not-writeable/file): failed to open stream: No such file or directory
C:\Users\Administrator\PhpstormProjects\untitled\ErrorSuppressionTest.php:18
C:\Users\Administrator\PhpstormProjects\untitled\ErrorSuppressionTest.php:10
ERRORS!
Tests: 1, Assertions: 0, Errors: 1.
关键字词:phpunit,php,错误,返回值
下一篇:phpunit对输出进行测试