【问题标题】:Laravel Testing - Throwing exception with MockeryLaravel 测试 - 用 Mockery 抛出异常
【发布时间】:2014-03-25 11:07:09
【问题描述】:

我对 Laravel 和一般的单元测试非常陌生。我正在尝试为我的 AccountController 编写一些测试,但遇到了障碍。

我正在使用 Sentry 来处理站点中的用户和组。我正在尝试测试我的控制器是否正确处理 Sentry 引发的异常。所以我处理登录 POST 的控制器方法如下所示:

public function postLogin(){

    $credentials = array(
        'email' => Input::get('email'),
        'password' => Input::get('password')
    );

    try{
        $user = $this->authRepo->authenticate($credentials, true);
        return Redirect::route('get_posts');
    }
    catch (Exception $e){
        $message = $this->getLoginErrorMessage($e);
        return View::make('login', array('errorMsg' => $message));
    }
}

authRepository 只是一个使用 Sentry 处理身份验证的存储库。现在我想测试当未指定电子邮件地址时,会引发 LoginRequiredException 并且用户会看到错误消息。这是我的测试:

public function testPostLoginNoEmailSpecified(){

    $args = array(
        'email' => 'test@test.com'
    );

    $this->authMock
        ->shouldReceive('authenticate')
        ->once()
        ->andThrow(new Cartalyst\Sentry\Users\LoginRequiredException);

    $this->action('POST', 'MyApp\Controllers\AccountController@postLogin', $args);

    $this->assertViewHas('errorMsg', 'Please enter your email address.');
}

但是,测试没有通过。出于某种原因,它吐出的只是:

There was 1 error:

1) AccountControllerTest::testPostLoginNoEmailSpecified
Cartalyst\Sentry\Users\LoginRequiredException: 

我是否错误地使用了 andThrow() 方法?如果有人能对正在发生的事情有所了解,将不胜感激。

提前致谢!

【问题讨论】:

  • 刚刚遇到了同样的问题。谢谢你的帖子!

标签: php unit-testing laravel mockery


【解决方案1】:

所以我实际上只是想出了问题所在。事实证明这根本不是我的单元测试的问题,而实际上只是一个命名空间问题。我忘记了 Exception 类的反斜杠。所以在我的控制器中应该是:

try{
    $user = $this->authRepo->authenticate($credentials, true);
    return Redirect::route('get_posts');
}
catch (\Exception $e){
    $message = $this->getLoginErrorMessage($e);
    return View::make('account.login', array('errorMsg' => $message));
}

【讨论】:

    猜你喜欢
    • 2020-08-18
    • 2014-09-05
    • 2014-05-10
    • 1970-01-01
    • 2013-09-08
    • 1970-01-01
    • 2020-06-02
    • 2019-04-15
    • 2013-09-08
    相关资源
    最近更新 更多