有人知道是否有断言或类似的东西可以测试被测试的代码中是否抛出了异常吗?
当前回答
你也可以在PHPUnit 9发布之前使用文档块注释:
class ExceptionTest extends PHPUnit_Framework_TestCase
{
/**
* @expectedException InvalidArgumentException
*/
public function testException()
{
...
}
}
对于PHP 5.5+(特别是带有命名空间的代码),我现在更喜欢使用::class
其他回答
另一种方法是:
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('Expected Exception Message');
请确保您的测试类扩展\PHPUnit_Framework_TestCase。
public function testException() {
try {
$this->methodThatThrowsException();
$this->fail("Expected Exception has not been raised.");
} catch (Exception $ex) {
$this->assertEquals("Exception message", $ex->getMessage());
}
}
您可以使用assertException扩展在一次测试执行期间断言多个异常。
插入方法到您的TestCase并使用:
public function testSomething()
{
$test = function() {
// some code that has to throw an exception
};
$this->assertException( $test, 'InvalidArgumentException', 100, 'expected message' );
}
我还为喜欢漂亮代码的人做了一个trait ..
下面的代码将测试异常消息和异常代码。
重要提示:如果没有抛出预期的异常,它将失败。
try{
$test->methodWhichWillThrowException();//if this method not throw exception it must be fail too.
$this->fail("Expected exception 1162011 not thrown");
}catch(MySpecificException $e){ //Not catching a generic Exception or the fail function is also catched
$this->assertEquals(1162011, $e->getCode());
$this->assertEquals("Exception Message", $e->getMessage());
}
你也可以在PHPUnit 9发布之前使用文档块注释:
class ExceptionTest extends PHPUnit_Framework_TestCase
{
/**
* @expectedException InvalidArgumentException
*/
public function testException()
{
...
}
}
对于PHP 5.5+(特别是带有命名空间的代码),我现在更喜欢使用::class
推荐文章
- 在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分析器?