2

I am working with a feature test and it's returning data correctly; all things are coming back correctly; and I'm at the final portion of my test.

I am struggling to assert that I'm getting back a ResourceCollection:

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

Here is the portion of my test:

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);

The error I get back is:

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

I'm not sure what I should be asserting in this case. I am getting back a resource collection, what should I be using instead? Thank you for any suggestions!

EDIT

Thank you @mare96! Your suggestion lead me to another approach that seemed to work. Which is great but I'm not too sure I really understand why...

Here's my full test (including my final assertion):

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());
}
4

1 回答 1

3

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

你可以这样做:

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

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

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

我希望至少我能帮上一点忙。

于 2020-04-10T11:29:17.727 回答