我已经使用Laravel一段时间了,我已经阅读了很多关于依赖注入的可测试代码.在谈到Facades和Mocked Objects时,我已经陷入了困惑.我看到两种模式:
class Post extends Eloquent {
protected $guarded = array();
public static $rules = array();
}
Run Code Online (Sandbox Code Playgroud)
这是我的帖子模型.我可以跑来Post::all();从我的博客上获取所有帖子.现在我想将它合并到我的控制器中.
我的第一直觉是将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 );
}
}
Run Code Online (Sandbox Code Playgroud)
我的单元测试看起来像这样:
<?php
use \Mockery;
class HomeControllerTest extends TestCase {
public function tearDown()
{
Mockery::close();
parent::tearDown();
}
public function testIndex()
{
$post_collection = new StdClass();
$post = …Run Code Online (Sandbox Code Playgroud)