【问题标题】:Mocking 2 data repositories at the same time with Laravel 4使用 Laravel 4 同时模拟 2 个数据存储库
【发布时间】:2014-03-30 02:06:59
【问题描述】:

我正在使用 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);

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

第一次嘲笑那个 Model 类是否以某种方式“丢失”了?

【问题讨论】:

  • 您能隔离问题吗?创建一个只包含这两行的测试: Mockery::mock('Pedido');和嘲弄::mock('Cliente');看看是否仍然找不到模型
  • 确保您是using 正确的namespaces。并尝试使用 App::make(repositories\canarias\PedidoDbRepository)

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


【解决方案1】:

事实证明,课程拼写错误确实是一个问题(我知道这是个白痴错误)。应该是

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

而不是

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-24
    • 2014-03-15
    • 2013-04-17
    • 1970-01-01
    相关资源
    最近更新 更多