LoginFormTest.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. }