繁体   English   中英

Laravel测试 - 与Mockery一起抛出异常

[英]Laravel Testing - Throwing exception with Mockery

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

提前致谢!

所以我实际上只是想出了问题。 事实证明,我的单元测试根本不是问题,但实际上只是一个命名空间问题。 我忘记了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));
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM