我正在尝试使用Behat的第一个功能,我正面临着我不知道如何实现预期异常的问题.
我发现问题https://github.com/Behat/Behat/issues/140和robocoder正在谈论一种可能的方式,Behat也使用它.但似乎他们并没有真正处理异常.
我的观点是实现强制异常处理.我不希望任何构造捕获所有异常并忘记它们.
一种可能的方法是:
When <player> transfers <transfer> from his account it should fail with <error>
履行
try {
...
} catch (\Exception $ex) {
assertEquals($error, $ex->getMessage());
}
我不喜欢场景描述.我想使用then关键字,例如
When <player> transfers <transfer> from his account
Then it should fail with error <error>
这种描述的缺点是我需要两种方法:
method1($arg1, $arg2) {
// Test the transfer
}
method2($arg1, $arg2) {
// Check if the exception is the right one
}
为了能够检入方法2,需要存储异常.
我看到的唯一可能的方法是使用try / catch并将其存储到变量中.
别人会抓住它而不采取任何措施.在运行测试时,没有人会注意到.
如何防止异常被丢弃?
有没有其他人实施类似的方案?
谢谢你的任何提示.
编辑:
Behat上下文:
playerTransfer($player, $amount) {
$player->transfer($amount);
}
实体类的方法:
transfer($amount) {
if ($this->getWealth() < $amount) {
throw NotEnoughMoney();
}
...
}
最佳答案 始终尝试将方法结果捕获到上下文类字段,例如:
//inside Behat context class method
try {
$this->outcome = $func();
}
catch(\Exception $ex) {
$this->outcome = $ex;
}
现在,当期待下一步的异常时,只需检查$this->结果是否是带有消息/代码的所需异常的实例.