use*_*033 5 php phpunit unit-testing cakephp cakephp-2.3
我想我必须在这里问一些帮助我的问题.我整个晚上都在这.我有这样的登录方法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' );
}
}
}
Run Code Online (Sandbox Code Playgroud)
我试图用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' );
}
Run Code Online (Sandbox Code Playgroud)
我还在学习使用CakePHP进行单元测试的基础知识.我收到此错误:
PHPUNIT_FRAMEWORK_ERROR_NOTICE
Undefined index: Location
Test case: UsersControllerTest(testLogin)
Run Code Online (Sandbox Code Playgroud)
我不知道是什么导致这个...我的测试方法有什么问题以及它应该如何编写?
谢谢!
我使用以下代码得到了这个工作:
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();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3123 次 |
| 最近记录: |