Jam*_*phy 6 php phpunit closures unit-testing
我编写了一个PHPUnit测试,用于检查调用方法时是否从闭包中抛出异常.闭包函数作为参数传递给方法,并从中抛出异常.
public function testExceptionThrownFromClosure()
{
try {
$this->_externalResourceTemplate->get(
$this->_expectedUrl,
$this->_paramsOne,
function ($anything) {
throw new Some_Exception('message');
}
);
$this->fail("Expected exception has not been found");
} catch (Some_Exception $e) {
var_dump($e->getMessage()); die;
}
}
Run Code Online (Sandbox Code Playgroud)
在ExternalResourceTemplate上指定的get函数的代码是
public function get($url, $params, $closure)
{
try {
$this->_getHttpClient()->setUri($url);
foreach ($params as $key => $value) {
$this->_getHttpClient()->setParameterGet($key, $value);
}
$response = $this->_getHttpClient()->request();
return $closure($response->getBody());
} catch (Exception $e) {
//Log
//Monitor
}
}
Run Code Online (Sandbox Code Playgroud)
有关为什么会调用fail assert语句的任何想法?你能不能捕获PHP中从闭包中抛出的异常,或者是否有一种我不知道的特定方式来处理它们.
对我来说,异常应该只是传播出返回堆栈,但它似乎没有.这是一个错误吗?仅供参考我正在运行PHP 5.3.3
感谢您的回答...
设法找出问题所在。看起来问题在于正在调用的 try-catch 块就是调用闭包的块。这是有道理的...
所以上面的代码应该是
public function get($url, $params, $closure)
{
try {
$this->_getHttpClient()->setUri($url);
foreach ($params as $key => $value) {
$this->_getHttpClient()->setParameterGet($key, $value);
}
$response = $this->_getHttpClient()->request();
return $closure($response->getBody());
} catch (Exception $e) {
//Log
//Monitor
throw new Some_Specific_Exception("Exception is actually caught here");
}
}
Run Code Online (Sandbox Code Playgroud)
所以看起来 PHP 5.3.3 并没有提到的 bug。我的错。
归档时间: |
|
查看次数: |
2400 次 |
最近记录: |