0

私は初めてモッキング/モッカリーに取り組んでいますが、次のテストが実際に私のコードに触れているのか、それとも私が作成したモックをテストしているだけなのかわからないのですか? また、このコードは名前がそのままの名前であるにもかかわらず、リポジトリ パターンに適切に適合していないことに気付きました..私はそれに取り組みます。

クラス:

<?php namespace Acme\Cart\Repositories;

class EloquentCartRepository{
    protected $model_name = 'CartModel';
    protected $model;
    public function __construct($model = null)
    {
        $this->model = is_null($model) ? new $this->model_name : $model;
    }

    public function create_visitor_cart($session_id,$type = 'main'){
        return $this->create('visitor',$session_id,$type);
    }
    protected function create($user_type = null,$user_identifier = null,$type = 'main')
    {
        if(is_null($user_identifier)) throw new \Exception('Cannot create create cart, missing user identifier');
        if(is_null($user_type)) throw new \Exception('Cannot create create cart, missing user type');
        if($user_type == 'visitor')
        {
            $this->model->user_session_id = $user_identifier;
        }
        else
        {
            $this->model->user_id = $user_identifier;
        }
        $this->model->type = $type;
        $this->model->save();
        return $this->model;
    }
}

そして私のテスト:

/** @test */
public function create_visitor_cart_calls_internal()
{
    $model = m::mock('Models\CartModel');
    $model->shouldReceive('user_session_id')->with('sess123');
    $model->shouldReceive('type')->with('main');
    $model->shouldReceive('save')->andReturn($model);

    $repository = new EloquentCartRepository($model);
    $created_model = $repository->create_visitor_cart('sess123','main');
    $this->assertEquals('sess123',$created_model->user_session_id);
    $this->assertEquals('main',$created_model->type);
}

これは私のクラスをテストする適切な方法ですか? それとも、これは嘲笑/嘲笑の誤った使用ですか?

4

1 に答える 1

0

返されたものをテストする代わりに、それが保存されていることをテストする必要があります。つまり、->save()実行されます。あなたが設定した期待値->save()は です$model->shouldReceive('save')->andReturn($model);。コードは の戻り値を使用しないため、これは意味がありません->save()

プログラミングでは、通常、コマンドとクエリの 2 種類のメソッドを扱います。クエリは何らかの値を取得し、何らかのロジックを実行して値を返すことができます。コマンドはいくつかの値を取得し、extern ソース (データベースなど) と通信して、何も返さないことがあります。クエリはスタブ化する必要があり (つまり、どれだけ呼び出されたかについて期待するのではなく、返されるものだけを期待する必要があります)、コマンドをモックする必要があります (つまり、どれだけ (および場合) についての期待のみを含める必要があります)。と呼ばれます)。

->save()メソッドはコマンドです。データベースと通信します。だから嘲笑されるべきです。オブジェクトをモックするには->once()、Mockery のメソッドを使用します。これは、1 回呼び出す必要があるという期待を設定します。

/** @test */
public function create_visitor_cart_calls_internal()
{
    $model = m::mock('Models\CartModel');
    $model->shouldReceive('save')->once();

    $repository = new EloquentCartRepository($model);
    $created_model = $repository->create_visitor_cart('sess123','main');
    $this->assertEquals('sess123',$created_model->user_session_id);
    $this->assertEquals('main',$created_model->type);
}

その名前にもかかわらず、Mockery はデフォルトでスタブ フレームワークです。次のような期待を明示的に指定しない限り、メソッドが呼び出されたことを検証しません->once()

詳細については、ドキュメントを参照してください: https://github.com/padraic/mockery-docs/blob/master/reference/expectations.rst

于 2014-03-25T21:04:13.660 に答える