如何断言 Laravel 中的 ResourceCollection 实例?

How can I assert an instance of a ResourceCollection in Laravel?

我正在进行功能测试,它可以正确返回数据;一切都恢复正常;我正处于测试的最后部分。

我很难断言我正在取回 ResourceCollection:

$this->assertInstanceOf(ResourceCollection::class, $response);

这是我的测试部分:

MyFeature.php

...

$http->assertStatus(200)
        ->assertJsonStructure([
            'data' => [
                '*' => [
                    'type', 'id', 'attributes' => [
                        'foo', 'bar', 'baz',
                    ],
                ],
            ],
            'links' => [
                'first', 'last', 'prev', 'next',
            ],
            'meta' => [
                'current_page', 'from', 'last_page', 'path', 'per_page', 'to', 'total',
            ],
        ]);

    // Everything is great up to this point...
    $this->assertInstanceOf(ResourceCollection::class, $response);

我返回的错误是:

Failed asserting that stdClass Object (...) is an instance of class "Illuminate\Http\Resources\Json\ResourceCollection".

我不确定在这种情况下我应该断言什么。我要取回一个资源集合,我应该使用什么来代替?感谢您的任何建议!

编辑

谢谢@mare96!您的建议使我想到了另一种似乎有效的方法。 很棒,但我不太确定我是否真的理解为什么...

这是我的完整测试(包括我的最终断言):

public function mytest() {
    $user = factory(User::class)->create();

    $foo = factory(Foo::class)->create();

    $http = $this->actingAs($user, 'api')
        ->postJson('api/v1/foo', $foo);

    $http->assertStatus(200)
        ->assertJsonStructure([
            'data' => [
                '*' => [
                    'type', 'id', 'attributes' => [
                        'foo', 'bar', 'baz'
                    ],
                ],
            ],
            'links' => [
                'first', 'last', 'prev', 'next',
            ],
            'meta' => [
                'current_page', 'from', 'last_page', 'path', 'per_page', 'to', 'total',
            ],
        ]);

    $this->assertInstanceOf(Collection::class, $http->getOriginalContent());
}

正如我在上面的评论中所说,您的内容将是 Collection 的实例。

你可以这样做:

$this->assertInstanceOf(Collection::class, $http->getOriginalContent());

所以,你可以尝试调试,让它更清楚,像这样:做 dd($http); 你应该得到一个 Illuminate\Foundation\Testing\TestResponse 的实例,当你做 $http->dump(); 时,你应该得到一个不一样的实例?

因此您需要声明一个仅包含内容的实例,而不是整个响应。

我希望至少我帮了一点忙。