0

コンストラクターを介して注入された Eloquent モデルを持つリポジトリーをテストする必要があります。

class EloquentOrderRepository implements OrderRepositoryInterface
{

    protected $model;

    public function __construct(Order $model)
    {
        $this->model = $model;
    }

    public function calculateValues(array $deliveryOption = null)
    {
        if (! is_null($deliveryOption)) {
            $this->model->value_delivery = (float) number_format($deliveryOption['price'], 2);
        }

        $this->model->value_products = (float) number_format($this->model->products->getTotal(), 2);
        $this->model->value_total    = (float) $this->model->value_products + $this->model->value_delivery;
    }
}

私の問題は、$this->model->value_products(または属性のいずれか)を呼び出すときです。setAttributeEloquent モデルは、モックされたモデルには存在しないメソッドを呼び出そうとします。このメソッドをモックすると、属性を正​​しく設定できず、テスト アサーションが失敗します。

これが私のテストです:

<?php
class EloquentOrderRepositoryTest extends \PHPUnit_Framework_TestCase
{

    protected $model, $repository;

    public function setUp()
    {
        $this->model = Mockery::mock('Order');
    }

    public function test_calculate_values()
    {
        $repository = new EloquentOrderRepository($this->model);

        $this->model->products = m::mock('SomeCollection');
        $this->model->products->shouldReceive('getTotal')->once()->withNoArgs()->andReturn(25);

        $this->model->calculateValues(array('price' => 12));
        $this->assertEquals(12, $this->model->value_delivery);
        $this->assertEquals(25, $this->model->value_products);
        $this->assertEquals(37, $this->model->value_total);
    }
}

これについて何か考えはありますか?

4

1 に答える 1

4

あなたの主な問題は、リポジトリ パターンを正しく使用していないことだと思います。コンストラクターで渡されたモデルをプロトタイプと考える必要があります。これは実際に使用するものではありませんが、他の目的で使用するもののインスタンスです。リポジトリには、次のような処理を行うメソッド getUnpaidOrders がある場合がありますreturn $this->model->wherePaid('0')->get();。ご覧のとおり、インスタンスを実際の具体的なインスタンスとして操作するのではなく、より広いスコープを実現するためのものです。

calculate メソッドでは、実際にこのプロトタイプ モデルに値を設定しています。あなたがこれらで何をしようとしているのかはわかりませんが、私が知る限り、これはリポジトリパターンが行うべきことではありません. リポジトリのメソッドは一般的に静的なメソッドであり、それらを呼び出して (おそらく入力を使用して) 何かを取得します。リポジトリにはいかなる種類の内部状態もあってはならないため、それらはいかなる種類の内部状態にも影響を与えるべきではありません。

うまくいけば、これは理にかなっています。

于 2014-02-13T12:46:12.303 に答える