3

I need to mock Laravel's Eloquent\Model with Mockery and it is kind of tricky because it uses static methods.

I solved this issue with the following code but I wonder if there is a better/smarter way to do this.

<?php

use Ekrembk\Repositories\EloquentPostRepository;

class EloquentPostRepositoryTest extends TestCase {
    public function __construct()
    {
        $this->mockEloquent = Mockery::mock('alias:Ekrembk\Post');
    }

    public function tearDown()
    {
        Mockery::close();
    }

    public function testTumuMethoduEloquenttenAldigiCollectioniDonduruyor()
    {
        $eloquentReturn = 'fake return';
        $this->mockEloquent->shouldReceive('all')
                     ->once()
                     ->andReturn($eloquentDongu);
        $repo = new EloquentPostRepository($this->mockEloquent);

        $allPosts = $repo->all();
        $this->assertEquals($eloquentReturn, $allPosts);
    }
}
4

1 回答 1

4

如果没有“Ekrembk\Repositories\EloquentPostRepository”的来源,很难说,但是,我看到了几个问题。看起来在您的 EloquentPostRepository 中,您正在调用静态。你不应该那样做。它使测试变得困难(正如您所发现的)。假设 Ekrembk\Post 从 Eloquent 扩展而来,您可以这样做:

<?php 
namespace Ekrembk\Repositories

class EloquentPostRepository {

    protected $model;

    public __construct(\Ekrembk\Post $model) {
        $this->model = $model;
    }   

    public function all()
    {
        $query = $this->model->newQuery();

        $results = $query->get();

        return $results;
    }

}

然后,您的测试会更简单:

<?php

use Ekrembk\Repositories\EloquentPostRepository;

class EloquentPostRepositoryTest extends TestCase {

    public function tearDown()
    {
        Mockery::close();
    }

    public function testTumuMethoduEloquenttenAldigiCollectioniDonduruyor()
    {
        $mockModel = Mockery::mock('\Ekrembk\Post');
        $repo = new EloquentPostRepository($mockModel);
        $eloquentReturn = 'fake return';

        $mockModel->shouldReceive('newQuery')->once()->andReturn($mockQuery = m::mock(' \Illuminate\Database\Eloquent\Builder'));

        $result = $mockQuery->shouldReceive('get')->once()->andReeturn($eloquentReturn);

        $this->assertEquals($eloquentReturn, $result);
    }
}

没有测试上面的,所以它可能有问题,但你应该明白。

如果您查看 Illuminate\Database\Eloquent\Model,您会发现“public static function all”实际上只是在实例化的 eloquent 模型上调用“get”。

于 2014-02-28T20:22:27.350 回答