我似乎无法正确执行此操作,异常的错误消息只是打印出来,使命令行窗口更难阅读。下面是我的代码结构和测试代码。
public function availableFruits($fruit)
{
switch($fruit) {
case 'foo':
// all good
break;
case 'bar':
// all good
break;
default:
throw new Exception($fruit.' not available!');
break;
}
}
public function chooseFruit($fruit)
{
try {
availableFruits($fruit);
} catch (Exception $e) {
echo $e->getMessage();
}
}
public function testAvailableFruits()
{
$this->setExpectedException('Exception');
chooseFruit('Kiwi');
}
错误消息将在命令行窗口中打印出来,如下所示。我尝试了phpunit.de中显示的所有方法,但结果相同。
..Error on line 13 in c:\file\path\fruits.php: Kiwi not available!.F
错误行打印出来,我如何压制它,我是否正确行事?
答案 0 :(得分:4)
我认为另一种方法是在测试方法中添加注释块,看起来像......
/**
* @expectedException ExpectedExceptionName
*/
或者,如果你没有进入catch块,你也可以捕获你自己导致方法失败的异常。
答案 1 :(得分:1)
这很令人尴尬,因为我发现了这样做的方法。谢谢克里斯,但我也试过了。
我测试了错误的方法,selectFruit不是抛出异常的方法,因此打印出异常错误:
public function testAvailableFruits()
{
$this->setExpectedException('Exception');
**chooseFruit('Kiwi');**
}
测试抛出异常的实际方法会使错误消息静音,因为它根本没有回显:
public function testAvailableFruits()
{
$this->setExpectedException('Exception');
**availableFruits('Papaya')**
}