使用Mockery测试Laravel View作曲家

时间:2018-11-12 14:14:48

标签: laravel mockery

我正在尝试测试View Composers。每当我将对象传递到$view->with('string', $object)时,测试都会失败。这是我进行如下测试的时间:

$view
    ->shouldReceive('with')
    ->with('favorites', $this->user->favorites(Ad::class)->get())
    ->once();

我敢肯定,这是由于严格检查造成的。于是我环顾四周,看到了this issue。但是,我似乎无法正常工作。闭包返回true,但是测试失败:

  

Mockery \ Exception \ InvalidCountException:具有('favorites',   应该调用Mockery_3_Illuminate_View_View中的)   正好1次却被调用0次。

这是我目前的考试

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类:

public function compose(View $view)
{
    $user = Auth::user();

    $favorites = $user 
        ? $user->favorites(Ad::class)->get()
        : collect([]);

    $view->with('favorites', $favorites);
}

如何测试这样的对象?

1 个答案:

答案 0 :(得分:0)

我通过将$view->with('favorites', $favorites);替换为$view->with(['favorites' => $favorites]);,然后像这样进行测试来解决了这个问题:

$view
    ->shouldReceive('with')
    ->with(['favorites' => $this->user->favorites(Ad::class)->get()])
    ->once();

因此,实际上,在with()方法中仅使用一个参数对我来说是固定的。