0

Posts クラスと Blog クラスがあります。

以下からわかるように、Posts クラスは Blog クラスに依存しています。

public function index(Blog $blog) {
    $posts = $this->post->all()->where('blog_id', $blog->id)->orderBy('date')->paginate(20);
    return View::make($this->tmpl('index'), compact('blog', 'posts'));
}

このアクションの URL は次のとおりです。

http://example.com/blogs/[blog_name]/posts

これをテストしようとしていますが、問題が発生しています。

これが私のテスト クラス PostTestController です。

public function setUp() {
    parent::setUp();
    $this->mock = Mockery::mock('Eloquent', 'Post');
}

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

public function testIndex() {

    $this->mock->shouldReceive('with')->once();

    $this->app->instance('Post', $this->mock);

    // get posts url
    $this->get('blogs/blog/posts'); //this is where I'm stuck.

    $this->assertViewHas('posts');
}

問題はこれです... get 自体にデータに基づく変数出力が含まれている場合、get 呼び出しをテストするにはどうすればよいですか? これを正しくテストするにはどうすればよいですか?

4

1 に答える 1

0

まず、コードにエラーがあります。all() を削除できます。

$posts = $this->post
  ->where('blog_id', $blog->id)
  ->orderBy('date')
  ->paginate(20);

2 つ目は、ルート モデル バインディングを単体テストする方法がわからないので、変更public function index(Blog $blog)してから、またはそれらの線に沿って何かpublic function index($blogSlug)を実行することです。$this->blog->where('slug', '=', $blogSlug)->first()

3 番目にm::mock('Post')、Eloquent ビットをドロップするだけです。これで問題が発生した場合は、 を実行してくださいm::mock('Post')->makePartial()

完全にすべてをテストしたい場合、テストは大まかに次のようになります。

use Mockery as m;

/** @test */
public function index()
{
    $this->app->instance('Blog', $mockBlog = m::mock('Blog'));
    $this->app->instance('Post', $mockPost = m::mock('Post'));
    $stubBlog = new Blog(); // could also be a mock
    $stubBlog->id = 5;
    $results = $this->app['paginator']->make([/* fake posts here? */], 30, 20);
    $mockBlog->shouldReceive('where')->with('slug', '=', 'test')->once()->andReturn($stubBlog);
    $mockPost->shouldReceive('where')->with('blog_id', '=', 5)->once()->andReturn(m::self())
        ->getMock()->shouldReceive('orderBy')->with('date')->once()->andReturn(m::self())
        ->getMock()->shouldReceive('paginate')->with(20)->once()->andReturn($results);

    $this->call('get', 'blogs/test/posts');
    // assertions
}

これは、データベース レイヤーに結合されたレイヤーの単体テストが難しいことを示す良い例です (この場合、Blog および Post モデルはデータベース レイヤーです)。代わりに、テスト データベースをセットアップし、ダミー データをシードしてテストを実行するか、データベース ロジックをリポジトリ クラスに抽出し、それをコントローラーに挿入して、モデルの代わりにそれをモックします。

于 2014-05-22T12:51:16.000 に答える