我已经使用 Laravel 有一段时间了,并且我已经阅读了很多关于依赖注入的可测试代码。在谈论 Facades 和 Mocked Objects 时,我感到困惑。我看到两种模式:
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 Mocks。对此问题的任何钙化将不胜感激。