单元测试未触发 try/catch 语句

Unit test not triggering try/catch statement

下面 class 的测试失败并出现以下错误。

 Method error() from Mockery_15_Illuminate_Log_Writer should be called exactly 1 times but called 0 times.

我正在尝试断言 ModelNotFoundException 已抛出并且 catch 部分中的代码正在 运行。似乎异常被正确抛出,但由于某种原因它停在那里。我在文档中找不到任何关于此的内容,但这是我第一次测试 try/catch,所以我可能只是遗漏了一些东西。

提前致谢。如果您需要更多信息,请告诉我。

注意:$this->userRepo 是一个通过构造函数注入的模拟对象。以防万一。

Class:

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']);
}

配置 mock 以抛出异常时,必须使用完全限定名称引用异常 class,即包括命名空间。如果你不这样做,class 将不相同,异常将被默认捕获捕获。