5

ここで私の問題に対する助けを求めなければならないと思いました。私はこれで一晩中過ごしました。UsersController次のようなログイン方法があります。

public function login() {

        if ( $this->request->is( 'post' ) ) {
            if ( $this->Auth->login() ) {
                $this->redirect( array( 'controller' => 'reservations', 'action' => 'index' ) );
            } else {
                $this->Session->setFlash( __( 'Login error.' ), 'flashError' );
            }
        }
    }

これをPHPUnitでテストしようとしているので、有効なユーザーのみがログインできることを確認できます→ログインに成功すると、特定のページにリダイレクトされます。クラスでの私のtestLoginメソッドは次のとおりです。UsersControllerTest

function testLogin() {

        $UsersController = $this->generate( 'Users', array(
                'components' => array(
                    'Auth' => array( 'user' )
                ),
            )
        );

        $UsersController->Auth->expects( $this->any() )
        ->method( 'user' )
        ->with( 'id' )
        ->will( $this->returnValue( 2 ) );

        $data = array( 'User' => array(
                'student_number' => 1111111,
                'password' => 'qwerty'
            ) );

        //$UsersController->Auth->login( $data['User'] );

        $this->testAction( '/users/login', array( 'data' => $data, 'method' => 'get' ) );
        $url = parse_url( $this->headers['Location'] );
        $this->assertEquals( $url['path'], '/reservations' );
    }

私はまだ CakePHP を使った単体テストの基礎を学んでいます。次のエラーが表示されます。

PHPUNIT_FRAMEWORK_ERROR_NOTICE
Undefined index: Location
Test case: UsersControllerTest(testLogin)

何が原因なのかわかりません... テストメソッドのどこが間違っているのでしょうか?どのように記述すればよいのでしょうか?

ありがとう!

4

2 に答える 2

2

次のコードでこれを機能させました:

function testLogin() {

        //mock user
        $this->Users = $this->generate( 'Users', array(
                'components' => array(
                    'Security' => array( '_validatePost' ),
                )
            ) );

        //create user data array with valid info
        $data = array();
        $data['User']['student_number'] = 1234567;
        $data['User']['password'] = '[valid password here]';

        //test login action
        $result = $this->testAction( "/users/login", array(
                "method" => "post",
                "return" => "contents",
                "data" => $data
            )
        );

        $foo[] = $this->view;
        //debug($foo);

        //test successful login
        $this->assertNotNull( $this->headers['Location'] );
        $this->assertContains( 'reservations', $this->headers['Location'] );
        $this->assertNotContains( '"/users/login" id="UserLoginForm"', $foo );

        //logout mocked user
        $this->Users->Auth->logout();
    }
于 2013-04-03T05:03:58.257 に答える