使用Laravel 4同时模拟2个数据存储库

时间:2014-02-26 22:40:17

标签: unit-testing laravel mocking phpunit repository-pattern

我正在使用Laravel 4开发一个应用程序,并试图遵循TDD。我按照Jeffrey Way或Philip Brown的教程使用我的数据库的存储库。之前我遇到过这个问题(Mockery not calling method from repository (interface)),但现在我的测试中一切正常。但是,我在同一个测试中尝试模拟2个存储库时遇到错误,如下所示:

class PedidosControllerTest extends TestCase {

    private $mock;
    private $pedidoModelMock;
    private $mockCliente;
    private $clienteModelMock;

    function setUp() {
        parent::setUp();
        $this->mock = $this->mock('repositories\canarias\PedidoDbRepository');
        $this->pedidoModelMock = Mockery::mock('Pedido');
        $this->mockCliente = $this->mock('repositories\canarias\ClienteDbRepository');
        $this->clienteModelMock = Mockery::mock('Cliente');
    }


    public function mock($class)
    {
        $mock = Mockery::mock('Model', $class);

        $this->app->instance($class, $mock);

        return $mock;
    }

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


    public function testIndexWithClient()
    {
        $nestedView = 'pedidos.index';
        $this->registerNestedView($nestedView);

        $this->mockCliente
            ->shouldReceive('find')
            ->once()
            ->with(698)
            ->andReturn($this->clienteModelMock);

        $this->mock
            ->shouldReceive('findAllFromCliente')
            ->once()
            ->with(698)
            ->andReturn($this->pedidoModelMock);

        $this->clienteModelMock
            ->shouldReceive('getAttribute')
            ->once()
            ->with('nombre')
            ->andReturn('Pepito');

        $this->call('GET', '/clientes/698/pedidos');
        $this->assertResponseOk();
        $this->assertViewHas('pageAttributes');
        $this->assertViewHas('contenido');
        $this->assertNestedViewHas($nestedView, 'pedidos');
        $this->assertNestedViewHas($nestedView, 'cliente');
   }
}

从我测试的内容(没有双关语意图),问题似乎与$ this-> mock和$ this-> mockCliente共享的代码有关:

Mockery :: mock('Model',$ class);

我收到错误,说Model类不存在。在测试的其他功能中,我只使用一个模拟,确实找到了该类,因此它与拼写错误的名称或类似的东西无关。

那个Model类在第一次被嘲笑时会以某种方式“丢失”吗?

1 个答案:

答案 0 :(得分:0)

事实证明,这个课程确实是一个问题,因为课程被误解了(我知道这是个蠢事)。它应该是

$this->mockCliente = $this->mock('repositories\canarias\ClientesDbRepository');

而不是

$this->mockCliente = $this->mock('repositories\canarias\ClienteDbRepository');