-1

This is the code that i am trying to test

    public function forgot($email)
{
    try
    {
        // Find the user using the user email address
        $user =$this->sentry->findUserByLogin($email);

        $resetCode = $user->getResetPasswordCode();

         return true;
    }
    catch (UserNotFoundException $e)
    {
        $this->errors[] = 'User was not found.';

        return false;
    }
}

Here is my testing code

  function it_should_forgot(Sentry $sentry)
{
    $email = 'johndavedecano@gmail.com';

    $sentry->findUserByLogin($email)->shouldBeCalled();

    $this->forgot($email);
}

Here is the error

PHP Fatal error:  Call to a member function getResetPasswordCode() on a non-object in /var/www/laravel/app/Services/SentryService.php on line 103

My question is why am i getting this error as i have already mock sentry inside my test?

John Dave Decano
  • 128
  • 1
  • 1
  • 5

1 Answers1

0

There's no mocking requried here. You only need stubs (Sentry) and dummies (User):

function it_returns_true_if_user_is_found(Sentry $sentry, User $user)
{
    $email = 'johndavedecano@gmail.com';

    $sentry->findUserByLogin($email)->willReturn($user);

    $this->forgot($email)->shouldReturn(true);
}

function it_returns_false_if_user_is_not_found(Sentry $sentry)
{
    $email = 'johndavedecano@gmail.com';

    $sentry->willThrow(new UserNotFoundException())->duringFindUserByLogin($email);

    $this->forgot($email)->shouldReturn(false);
}

Recommended reading:

Jakub Zalas
  • 35,761
  • 9
  • 93
  • 125