[英]Laravel & Mockery - Unit Testing Relational Data
我有一個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'));
}
此操作的網址如下:
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調用? 如何正確測試?
首先,您的代碼有錯誤。 您可以刪除all()。
$posts = $this->post
->where('blog_id', $blog->id)
->orderBy('date')
->paginate(20);
其次,我不知道一種對路由模型綁定進行單元測試的方法,因此我將public function index(Blog $blog)
更改為public function index($blogSlug)
,然后執行$this->blog->where('slug', '=', $blogSlug)->first()
或類似內容。
第三,只需執行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模型是數據庫層)。 相反,我將建立一個測試數據庫,將其與虛擬數據一起播種並對其進行測試,或者將數據庫邏輯提取到存儲庫類中,然后將其注入控制器中並模擬它而不是模型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.