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 に答える