codecamp

PHPUnit9.0 编写PHPUnit测试-对异常进行测试

示例 2.11 展示了如何用 ​@expectException​ 标注来测试被测代码中是否抛出了异常。

示例 2.11 使用 ​expectException()​ 方法

<?php declare(strict_types=1);
use PHPUnit\Framework\TestCase;

final class ExceptionTest extends TestCase
{
    public function testException(): void
    {
        $this->expectException(InvalidArgumentException::class);
    }
}
$ phpunit ExceptionTest
PHPUnit latest.0 by Sebastian Bergmann and contributors.

F

Time: 0 seconds, Memory: 4.75Mb

There was 1 failure:

1) ExceptionTest::testException
Failed asserting that exception of type "InvalidArgumentException" is thrown.

FAILURES!
Tests: 1, Assertions: 1, Failures: 1.

除了 ​expectException()​ 方法外,还有 ​expectExceptionCode()​、​expectExceptionMessage()​ 和 ​expectExceptionMessageMatches()​ 方法可以用于为被测代码所抛出的异常建立预期。

注意 ​expectExceptionMessage()​ 断言的是 ​$actual​ 讯息包含有 ​$expected​ 讯息,并不执行精确的字符串比较。


PHPUnit9.0 编写PHPUnit测试-数据供给器
PHPUnit9.0 编写PHPUnit测试-对PHP错误、警告和通知进行测试
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }