【发布时间】:2014-03-28 17:24:25
【问题描述】:
我使用 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');
}
}
我理解这两种方法,但我不明白为什么我应该或何时应该使用一种方法而不是另一种方法。例如,我尝试将 DI 路由与 Auth 类一起使用,但它不起作用,所以我必须使用 Facade Mocks。对此问题的任何钙化将不胜感激。
【问题讨论】:
标签: php unit-testing dependency-injection laravel-4 mockery