私はしばらくLaravelを使用しており、テスト可能なコードである依存性注入について多くのことを読んでいます。Facades と Mocked Objects について話すとき、私は混乱するところまで来ました。2 つのパターンが表示されます。
class Post extends Eloquent {
protected $guarded = array();
public static $rules = array();
}
これが私の投稿モデルです。実行Post::all();
して、ブログからすべての投稿を取得できました。今、私はそれを自分のコントローラーに組み込みたいと思っています。
オプション #1: 依存性注入
私の最初の本能は、Post
モデルを依存関係として注入することです。
class HomeController extends BaseController {
public function __construct(Post $post)
{
$this->post = $post;
}
public function index()
{
$posts = $this->posts->all();
return View::make( 'posts' , compact( $posts );
}
}
私の単体テストは次のようになります。
<?php
use \Mockery;
class HomeControllerTest extends TestCase {
public function tearDown()
{
Mockery::close();
parent::tearDown();
}
public function testIndex()
{
$post_collection = new StdClass();
$post = Mockery::mock('Eloquent', 'Post')
->shouldRecieve('all')
->once()
->andReturn($post_collection);
$this->app->instance('Post',$post);
$this->client->request('GET', 'posts');
$this->assertViewHas('posts');
}
}
オプション #2: ファサード モック
class HomeController extends BaseController {
public function index()
{
$posts = Post::all();
return View::make( 'posts' , compact( $posts );
}
}
私の単体テストは次のようになります。
<?php
use \Mockery;
class HomeControllerTest extends TestCase {
public function testIndex()
{
$post_collection = new StdClass();
Post::shouldRecieve('all')
->once()
->andReturn($post_collection);
$this->client->request('GET', 'posts');
$this->assertViewHas('posts');
}
}
私は両方の方法を理解していますが、なぜ、またはいつ一方の方法を他方よりも優先して使用する必要があるのか を理解していません。たとえば、Auth
クラスで DI ルートを使用しようとしましたが、機能しないため、Facade モックを使用する必要があります。この問題に関する石灰化は大歓迎です。