【问题标题】:Fatal error: Call to a member function when Mocking on PHPSpec致命错误:在 PHPSpec 上模拟时调用成员函数
【发布时间】:2014-10-24 20:56:50
【问题描述】:

这是我要测试的代码

    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;
    }
}

这是我的测试代码

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

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

    $this->forgot($email);
}

这是错误

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

我的问题是为什么我会收到这个错误,因为我已经在我的测试中模拟了哨兵?

【问题讨论】:

  • 那么你在哪里模拟 findUserByLogin 返回的内容?
  • 请告诉我应该怎么做。谢谢
  • 好吧,看看你的测试方法,告诉你findUserByLogin方法应该返回什么。
  • $sentry->findUserByLogin('johndavedecano@test.com')->willReturn($user);请让我知道这是否正确
  • 如果你先试试呢? Stackoverflow 并非旨在成为语法检查器

标签: php unit-testing laravel-4 phpspec


【解决方案1】:

这里不需要嘲笑。您只需要存根 (Sentry) 和假人 (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);
}

推荐阅读

【讨论】:

    猜你喜欢
    • 2011-08-22
    • 2018-06-22
    • 2020-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多