以下课程的测试失败,并出现以下错误。
Method error() from Mockery_15_Illuminate_Log_Writer should be called exactly 1 times but called 0 times.
我试图断言抛出ModelNotFoundException并且正在运行catch部分中的代码。似乎异常被正确抛出但由于某种原因它停在那里。我无法在文档中找到关于此的任何内容,但这是我第一次测试try / catch所以我可能只是遗漏了一些东西。
提前致谢。如果您需要更多信息,请告诉我。
注意:$ this-> userRepo是通过构造函数注入的模拟对象。如果不清楚的话。
类别:
public function fire()
{
try{
//if the userEmail option is specified, then only run that email for a specific user
if($this->option('userEmail')) {
// the point the exception is thrown
$user = $this->userRepo->findBy('email', $this->option('userEmail'));
// other non-important code
} else {
// other code
}
} catch(ModelNotFoundException $e) {
// the code that is not being run even when exception is thrown
$message = 'User with email of '. $this->option('userEmail'). ' does not exist in '. App::environment(). ' db';
\Log::error($message);
$this->error($message);
} catch(Exception $e) {
\Log::error($e->getMessage());
$this->error($e->getMessage());
}
}
测试:
public function email_reports_fail_to_send_if_no_model_found()
{
$this->setExpectedException('ModelNotFoundException');
$this->userRepo
->shouldReceive('findBy')
->once()
->with('email', 'whatAMadeUpEmailThisIsRidiculous@gmail.com')
->andThrow('ModelNotFoundException');
\Log::shouldReceive('error')->once();
$this->commandTester->execute(['command' => $this->command->getName(), '--userEmail' => 'whatAMadeUpEmailThisIsRidiculous@gmail.com']);
}
答案 0 :(得分:1)
配置模拟以抛出异常时,必须使用完全限定名称引用Exception类,即包括命名空间。如果不这样,那么类将不会相同,并且默认catch会捕获异常。