[英]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.