有人知道是否有断言或类似的东西可以测试被测试的代码中是否抛出了异常吗?
当前回答
您可以使用assertException扩展在一次测试执行期间断言多个异常。
插入方法到您的TestCase并使用:
public function testSomething()
{
$test = function() {
// some code that has to throw an exception
};
$this->assertException( $test, 'InvalidArgumentException', 100, 'expected message' );
}
我还为喜欢漂亮代码的人做了一个trait ..
其他回答
PhpUnit是一个很棒的库,但这一点有点令人沮丧。这就是为什么我们可以使用turbotesting-php开源库,它有一个非常方便的断言方法来帮助我们测试异常。在这里可以找到:
https://github.com/edertone/TurboTesting/blob/master/TurboTesting-Php/src/main/php/utils/AssertUtils.php
要使用它,我们只需执行以下操作:
AssertUtils::throwsException(function(){
// Some code that must throw an exception here
}, '/expected error message/');
如果我们在匿名函数中键入的代码没有抛出异常,则会抛出异常。
如果我们在匿名函数中键入的代码抛出异常,但其消息与预期的regexp不匹配,则也将抛出异常。
<?php
require_once 'PHPUnit/Framework.php';
class ExceptionTest extends PHPUnit_Framework_TestCase
{
public function testException()
{
$this->expectException(InvalidArgumentException::class);
// or for PHPUnit < 5.2
// $this->setExpectedException(InvalidArgumentException::class);
//...and then add your test code that generates the exception
exampleMethod($anInvalidArgument);
}
}
PHPUnit文档
PHPUnit作者文章提供了关于测试异常最佳实践的详细解释。
/**
* @expectedException Exception
* @expectedExceptionMessage Amount has to be bigger then 0!
*/
public function testDepositNegative()
{
$this->account->deposit(-7);
}
注意“/**”,注意两个“*”。只写“**”(星号)将使代码失败。 同时确保你使用的是phpUnit的最新版本。在phpunit的一些早期版本中,不支持@expectedException异常。我有4.0,它不适合我,我必须更新到5.5 https://coderwall.com/p/mklvdw/install-phpunit-with-composer更新与作曲家。
public function testException() {
try {
$this->methodThatThrowsException();
$this->fail("Expected Exception has not been raised.");
} catch (Exception $ex) {
$this->assertEquals("Exception message", $ex->getMessage());
}
}
以下是您可以执行的所有异常断言。注意,它们都是可选的。
class ExceptionTest extends PHPUnit_Framework_TestCase
{
public function testException()
{
// make your exception assertions
$this->expectException(InvalidArgumentException::class);
// if you use namespaces:
// $this->expectException('\Namespace\MyException');
$this->expectExceptionMessage('message');
$this->expectExceptionMessageRegExp('/essage$/');
$this->expectExceptionCode(123);
// code that throws an exception
throw new InvalidArgumentException('message', 123);
}
public function testAnotherException()
{
// repeat as needed
$this->expectException(Exception::class);
throw new Exception('Oh no!');
}
}
文档可以在这里找到。
推荐文章
- 在PHP单元测试执行期间,如何在CLI中输出?
- 在PHP中使用heredoc的优势是什么?
- PHP中的echo, print和print_r有什么区别?
- 如何获取在Python中捕获的异常的名称?
- 如何将XML转换成PHP数组?
- 如何将对象转换为数组?
- 断言是邪恶的吗?
- 从IP地址获取位置
- 如何使用try catch进行异常处理是最佳实践
- 获取数组值的键名
- HTTPS和SSL3_GET_SERVER_CERTIFICATE:证书验证失败,CA is OK
- PHP -获取bool值,当为false时返回false
- 如何处理AccessViolationException
- 在foreach中通过引用传递
- 如何触发命令行PHP脚本的XDebug分析器?