LoginFormTest.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. namespace tests\unit\models;
  3. use Yii;
  4. use yii\codeception\TestCase;
  5. use app\models\User;
  6. class LoginFormTest extends TestCase
  7. {
  8. use \Codeception\Specify;
  9. protected function tearDown()
  10. {
  11. Yii::$app->user->logout();
  12. parent::tearDown();
  13. }
  14. public function testLoginNoUser()
  15. {
  16. $model = $this->mockUser(null);
  17. $model->username = 'some_username';
  18. $model->password = 'some_password';
  19. $this->specify('user should not be able to login, when there is no identity' , function () use ($model) {
  20. expect('model should not login user', $model->login())->false();
  21. expect('user should not be logged in', Yii::$app->user->isGuest)->true();
  22. });
  23. }
  24. public function testLoginWrongPassword()
  25. {
  26. $model = $this->mockUser(new User);
  27. $model->username = 'demo';
  28. $model->password = 'wrong-password';
  29. $this->specify('user should not be able to login with wrong password', function () use ($model) {
  30. expect('model should not login user', $model->login())->false();
  31. expect('error message should be set', $model->errors)->hasKey('password');
  32. expect('user should not be logged in', Yii::$app->user->isGuest)->true();
  33. });
  34. }
  35. public function testLoginCorrect()
  36. {
  37. $model = $this->mockUser(new User(['password' => 'demo']));
  38. $model->username = 'demo';
  39. $model->password = 'demo';
  40. $this->specify('user should be able to login with correct credentials', function() use ($model) {
  41. expect('model should login user', $model->login())->true();
  42. expect('error message should not be set', $model->errors)->hasntKey('password');
  43. expect('user should be logged in', Yii::$app->user->isGuest)->false();
  44. });
  45. }
  46. private function mockUser($user)
  47. {
  48. $loginForm = $this->getMock('app\models\LoginForm',['getUser']);
  49. $loginForm->expects($this->any())->method('getUser')->will($this->returnValue($user));
  50. return $loginForm;
  51. }
  52. }