LoginFormTest.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. public function testLoginNoUser()
  10. {
  11. $model = $this->mockUser(null);
  12. $model->username = 'some_username';
  13. $model->password = 'some_password';
  14. $this->specify('user should not be able to login, when there is no identity' , function () use ($model) {
  15. expect('model should not login user', $model->login())->false();
  16. expect('user should not be logged in', Yii::$app->user->isGuest)->true();
  17. });
  18. }
  19. public function testLoginWrongPassword()
  20. {
  21. $model = $this->mockUser(new User);
  22. $model->username = 'demo';
  23. $model->password = 'wrong-password';
  24. $this->specify('user should not be able to login with wrong password', function () use ($model) {
  25. expect('model should not login user', $model->login())->false();
  26. expect('error message should be set', $model->errors)->hasKey('password');
  27. expect('user should not be logged in', Yii::$app->user->isGuest)->true();
  28. });
  29. }
  30. public function testLoginCorrect()
  31. {
  32. $model = $this->mockUser(new User(['password' => 'demo']));
  33. $model->username = 'demo';
  34. $model->password = 'demo';
  35. $this->specify('user should be able to login with correct credentials', function() use ($model) {
  36. expect('model should login user', $model->login())->true();
  37. expect('error message should not be set', $model->errors)->hasntKey('password');
  38. expect('user should be logged in', Yii::$app->user->isGuest)->false();
  39. });
  40. }
  41. private function mockUser($user)
  42. {
  43. $loginForm = $this->getMock('app\models\LoginForm',['getUser']);
  44. $loginForm->expects($this->any())->method('getUser')->will($this->returnValue($user));
  45. return $loginForm;
  46. }
  47. }