【问题标题】:Mocking Password facade in Laravel 4在 Laravel 4 中模拟密码门面
【发布时间】:2015-04-10 14:33:46
【问题描述】:

我正在尝试为几个控制器操作编写 phpunit 测试。除了嘲笑密码门面之外,一切似乎都很好。

其中一个操作(“忘记密码”)如下所示:

if (Auth::check())
    //return a redirect since the user is already logged in

switch ($response = Password::remind(Input::only('email')))
{
    case Password::INVALID_USER:
        //return a redirect with error messages

    case Password::REMINDER_SENT:
        //return a redirect with success message flushed
}

Auth 和 Password 都是门面,默认是 Laravel 自带的。

测试Auth::check() 部分工作正常:

Auth::shouldReceive('check')->
    once()->
    andReturn(false);  //or true depending on my test case

但是当我尝试对Password::remind() 调用相同的尝试时,它不起作用:

Password::shouldReceive('remind')->
    once()->
    andReturn(Password::INVALID_USER);

我收到“SQLSTATE Access denied”异常,这意味着应用程序正在尝试访问数据库。

我还尝试将with(array()) 添加到我的测试中,甚至绑定Mockery::mock('\Illuminate\Auth\Reminders\PasswordBroker') - 这些都没有帮助。

如何测试这个控制器动作?为什么 Password 外观与 Auth 不同?我还应该尝试什么?

谢谢

【问题讨论】:

    标签: php testing laravel phpunit mockery


    【解决方案1】:

    所以我做了更多的搜索、编码和调查。我终于成功了,尽管它应该按照我最初的预期工作。

    我在 Laravel 文档中读到调用 Facade::shouldReceive('method') 应该返回一个 Mockery 对象。所以我在我的测试中尝试了这个:

    var_dump(get_class(Auth::shouldReceive('check')));
    var_dump(get_class(Password::shouldReceive('remind')));
    

    第一个按预期工作,但密码一个没有。因此,在阅读了更多网页,浏览了 Laravel 的门面和服务提供商之后,我终于想出了一些东西。

    我模拟了一个 PasswordBroker 对象(这就是 Password 门面所指的)并将它“引入”到 IoC。

    $this->authReminder = Mockery::mock('Illuminate\Auth\Reminders\PasswordBroker');
    App::instance('auth.reminder', $this->authReminder);
    

    然后我使用这个对象而不是像这样的密码门面:

    $this->authReminder->
        shouldReceive('remind')->
        once()->
        andReturn(Password::INVALID_USER);
    

    我知道这并不能解释为什么外观模拟不适用于 Password,但至少经过数小时的努力,我能够编写我需要的测试并继续该项目。

    【讨论】:

      猜你喜欢
      • 2018-06-25
      • 2016-05-02
      • 1970-01-01
      • 2023-03-26
      • 2020-06-01
      • 2013-10-02
      • 1970-01-01
      • 2014-02-17
      • 2014-01-09
      相关资源
      最近更新 更多