LoginFormTest.php 1.6 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. $this->assertFalse($model->login());
  16. $this->assertTrue(Yii::$app->user->isGuest,'user should not be logged in');
  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. $this->assertFalse($model->login());
  26. $this->assertArrayHasKey('password', $model->errors);
  27. $this->assertTrue(Yii::$app->user->isGuest, 'user should not be logged in');
  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. $this->assertTrue($model->login());
  37. $this->assertArrayNotHasKey('password', $model->errors);
  38. $this->assertFalse(Yii::$app->user->isGuest,'user should be logged in');
  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. }