10

我试图用嘲弄来模拟雄辩的模型。模型通过注入控制器

__construct(Post $model){$this->model=$model}

现在我find()在控制器中调用函数

$post = $this->model->find($id);

这是 PostsController 的测试

class PostsTest extends TestCase{

      protected $mock;

      public function setUp() {
        parent::setUp();
        $this->mock = Mockery::mock('Eloquent', 'Posts'); /*According to Jeffrey Way you have to add Eloquent in this function call to be able to use certain methods from model*/
        $this->app->instance('Posts', $this->mock);
      }

      public function tearDown() {

        Mockery::close();
      }

      public function testGetEdit()
      {
        $this->mock->shouldReceive('find')->with(1)->once()->andReturn(array('id'=>1));

        $this->call('GET', 'admin/posts/edit/1');

        $this->assertViewHas('post', array('id'=>1));
      }
    }

运行 PhpUnit 给我错误:

Fatal error: Using $this when not in object context in ...\www\l4\vendor\mockery\mockery\library\Mockery\Generator.php(130) : eval()'d code on line 73

这显然是因为find()被声明为静态函数。现在,代码可以正常工作,所以我怎样才能成功地模拟 Eloquent 模型而不会失败。由于我们依赖依赖注入,所以我必须find()非静态调用,否则我只能做Post::find().

我想出的一种解决方案是find()BaseModel

public function nsFind($id, $columns = array('*'))
{
  return self::find($id, $columns);
}

但这是一个很大的痛苦,因为函数必须有不同的名称!

我做错了什么还是你有更好的想法?

4

3 回答 3

8

模拟 Eloquent 模型是一件非常棘手的事情。它在书中有所介绍,但我特别指出这是一个权宜之计。最好使用存储库。

但是,要回答您的问题,问题是您没有在构造函数中执行模拟。这是让它工作的唯一方法。这并不理想,我不会推荐它。

于 2013-06-18T14:44:59.667 回答
2

我认为这就是原因,Jeffrey 在他的书 Laravel 测试解码(第 10 章)中介绍了存储库。

Mockery 在其 README 中也有关于静态方法的部分,请参阅https://github.com/padraic/mockery#mocking-public-static-methods

于 2013-06-09T10:53:29.507 回答
1

有一种方法可以做到这一点。(Laravel 版本为 5.8)

假设你有一个基类:

<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model as EloquentModel;
use Mockery\Mock;

/**
 * Base class of all model classes, to implement Observers or whatever filters you will need
 */
class Model extends EloquentModel
{

    protected static $mocks = [];

    /**
     * @return Mock
     */
    public static function getMock()
    {
        if (isset(self::$mocks[static::class])) {
            return self::$mocks[static::class];
        }
        self::$mocks[static::class] = \Mockery::mock(static::class)->makePartial()->shouldAllowMockingProtectedMethods();
        return self::$mocks[static::class];
    }

    public static function removeMock(): void
    {
        if (isset(self::$mocks[static::class])) {
            unset(self::$mocks[static::class]);
        }
    }

    public static function deleteMocks() : void
    {
        self::$mocks = [];
    }

    public static function __callStatic($method, $parameters)
    {
        /**
         * call the mock's function
         */
        if (isset(self::$mocks[static::class])) {
            return self::$mocks[static::class]->$method(...$parameters);
        }
        return parent::__callStatic($method, $parameters);
    }


}

一个模型是:

<?php
namespace App\Model;

class Accounts extends Model
{
    /**
     * @var  string
     */
    protected $table = 'accounts';
    /**
     * @var  string
     */
    protected $primaryKey = 'account_id';

    /**
     * attributes not writable from outside
     * @var  mixed
     */
    protected $guarded = ['account_id'];
}

然后是一个服务类,为您提供数据库中的帐户:

<?php


namespace App\Service;

use App\Model\Accounts;

class AccountService
{
    public function getAccountById($id): ?Accounts
    {       
       return Accounts::find($id);       
    }

}

让我们不讨论这个测试有多么有用,但我相信你会明白它的要点并看到你不再需要数据库,因为我们在“全局静态”范围内劫持了 find 方法。

然后测试看起来像这样:

<?php
namespace Tests\Unit\Services;

use App\Model\Accounts;
use App\Service\AccountService;
use Tests\TestCase;

class AccountServiceTest extends TestCase
{
    public function testGetAccountById()
    {
        $staticGlobalAccountMock = Accounts::getMock();
        $staticGlobalAccountMock->shouldReceive('find')
                ->andReturn(new Accounts(
                        ['account_id' => 123, 
                         'account_fax' => '056772']));
        $service = new AccountService();
        $ret = $service->getAccountById(123);
        $this->assertEquals('056772',$ret->account_fax);
        //clean up all mocks or just this mock
        Accounts::deleteMocks();
    }

}
于 2019-11-13T06:15:36.473 回答