【问题标题】:How to mock Auth in a Laravel 5.2 Model如何在 Laravel 5.2 模型中模拟 Auth
【发布时间】:2016-01-27 15:33:55
【问题描述】:

我正在尝试为一个全新的迷你应用编写一些单元测试。我通常编写功能测试,所以这是我的分支,尝试使用模拟和存根以及所有那些使它成为代码的东西正确地完成它。

模型如下所示:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Auth;

class myModel extends Model
{
    public static function getUser()
    {
        $user = \Auth::user();
        return $user->adldapUser->cn[0];
    }
}

还有测试:

class MyModelTest extends TestCase
{

    public function testGetUser()
    {
        $mockResult = new StdClass();
        $mockResult->adldapUser = new stdClass();
        $mockResult->adldapUser->cn=array("test");
        $auth = $this->getMock('Auth');
        $auth
            ->method('user')
            ->will($this->returnValue($mockResult));

        $this->assertEquals('test',\App\MyModel::getUser());
    }
}

但是当我运行单元测试时,我收到以下错误消息:

有 1 个错误:

1) MyModelTest::testGetUser ErrorException: Trying to get property of 非对象

/home/aidan/web/vagrant-web-dev/src/apps/orcid/app/MyModel.php:61 /home/aidan/web/vagrant-web-dev/src/apps/orcid/tests/MyModelTest.php:18

如果我发布 $user 它是 NULL。

我在这里做错了什么?

【问题讨论】:

    标签: php unit-testing laravel-5 model mocking


    【解决方案1】:

    问了半小时后,我又来回答我自己的问题了。

    为了繁荣,我把它留在这里。

    答案在这篇文章中:https://stackoverflow.com/a/17602763/808124

    所以我将 $this->getMock 替换为

    Auth::shouldReceive('user')->once()->andreturn($mockResult);
    

    工作

    【讨论】:

      【解决方案2】:

      我是这样用的:

      $user -factory(User:class)->create();
      \Auth::shouldReceive('guard')->andReturnSelf()
               ->shouldReceive('user')->andReturn($user)
               ->shouldReceive('check')->andReturn(true);
      

      【讨论】:

        猜你喜欢
        • 2020-06-09
        • 2016-11-01
        • 2016-07-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-08
        • 2023-03-22
        相关资源
        最近更新 更多