使用 Mockery 测试 Laravel View Composer
Testing Laravel View Composers with Mockery
我正在尝试测试我的 View Composer。每当我将对象传递给 $view->with('string', $object)
时,我的测试都会失败。这是我像这样进行测试的时候:
$view
->shouldReceive('with')
->with('favorites', $this->user->favorites(Ad::class)->get())
->once();
我很确定这是由于严格的检查。所以我环顾四周,看到了this issue。但是,我似乎无法让它工作。闭包 return 为真,但测试失败:
Mockery\Exception\InvalidCountException : Method with('favorites',
< Closure===true >) from Mockery_3_Illuminate_View_View should be called
exactly 1 times but called 0 times.
这是我目前的测试
public function it_passes_favorites_to_the_view()
{
$this->setUpUser(); // basically sets $this->user to a User object
Auth::shouldReceive('user')
->once()
->andReturn($this->user);
$composer = new FavoritesComposer();
$view = Mockery::spy(View::class);
$view
->shouldReceive('with')
->with('favorites', Mockery::on(function($arg) {
$this->assertEquals($this->user->favorites(Ad::class)->get(), $arg);
}))
->once();
$composer->compose($view);
}
FavoritesComposer class:
public function compose(View $view)
{
$user = Auth::user();
$favorites = $user
? $user->favorites(Ad::class)->get()
: collect([]);
$view->with('favorites', $favorites);
}
如何测试这样的对象?
我通过用 $view->with(['favorites' => $favorites]);
替换 $view->with('favorites', $favorites);
解决了这个问题,然后像这样测试它:
$view
->shouldReceive('with')
->with(['favorites' => $this->user->favorites(Ad::class)->get()])
->once();
所以,基本上只使用 with()
方法中的一个参数就是为我修复它的方法。
我正在尝试测试我的 View Composer。每当我将对象传递给 $view->with('string', $object)
时,我的测试都会失败。这是我像这样进行测试的时候:
$view
->shouldReceive('with')
->with('favorites', $this->user->favorites(Ad::class)->get())
->once();
我很确定这是由于严格的检查。所以我环顾四周,看到了this issue。但是,我似乎无法让它工作。闭包 return 为真,但测试失败:
Mockery\Exception\InvalidCountException : Method with('favorites', < Closure===true >) from Mockery_3_Illuminate_View_View should be called exactly 1 times but called 0 times.
这是我目前的测试
public function it_passes_favorites_to_the_view()
{
$this->setUpUser(); // basically sets $this->user to a User object
Auth::shouldReceive('user')
->once()
->andReturn($this->user);
$composer = new FavoritesComposer();
$view = Mockery::spy(View::class);
$view
->shouldReceive('with')
->with('favorites', Mockery::on(function($arg) {
$this->assertEquals($this->user->favorites(Ad::class)->get(), $arg);
}))
->once();
$composer->compose($view);
}
FavoritesComposer class:
public function compose(View $view)
{
$user = Auth::user();
$favorites = $user
? $user->favorites(Ad::class)->get()
: collect([]);
$view->with('favorites', $favorites);
}
如何测试这样的对象?
我通过用 $view->with(['favorites' => $favorites]);
替换 $view->with('favorites', $favorites);
解决了这个问题,然后像这样测试它:
$view
->shouldReceive('with')
->with(['favorites' => $this->user->favorites(Ad::class)->get()])
->once();
所以,基本上只使用 with()
方法中的一个参数就是为我修复它的方法。