9

我对 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() 方法?如果有人能对正在发生的事情有所了解,将不胜感激。

提前致谢!

4

1 回答 1

15

所以我实际上只是想出了问题所在。事实证明这根本不是我的单元测试的问题,而实际上只是一个命名空间问题。我忘记了 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));
}
于 2014-02-24T01:24:28.340 回答