[英]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.