phpunit 测试资源 laravel 5.5 返回集合而不是 json

Posted

技术标签:

【中文标题】phpunit 测试资源 laravel 5.5 返回集合而不是 json【英文标题】:phpunit testing resource laravel 5.5 returns collection instead a json 【发布时间】:2018-07-01 04:25:15 【问题描述】:

当我通过邮递员访问我的 api 时返回 json。但是,当我尝试使用 phpunit 返回集合进行测试时。

我正在使用 laravel 5.5 和资源来转换数据。

邮递员回复:


    "data": [
        
            "id": 1,
            "name": "Admin",
            "email": "admin@gmail.com",
            "role": [
                
                    "id": 1,
                    "name": "admin"
                
            ]
        
    ],
    "links": 
        "first": "http://localhost:8000/api/admin/users?page=1",
        "last": "http://localhost:8000/api/admin/users?page=2",
        "prev": null,
        "next": "http://localhost:8000/api/admin/users?page=2"
    ,
    "meta": 
        "current_page": 1,
        "from": 1,
        "last_page": 2,
        "path": "http://localhost:8000/api/admin/users",
        "per_page": "1",
        "to": 1,
        "total": 2
    

我的phpunit函数:

$this->get('api/admin/users')
            ->assertStatus(200)
            ->assertJsonCount(count($users));

使用 php 单元来自 uri $this->get('api/admin/users') 的响应:

Illuminate\Foundation\Testing\TestResponse #39
  +baseResponse: Illuminate\Http\JsonResponse #1347
    #data: ""data":["id":1,"name":"Watson Cole","email":"ralph.mayert@example.com","role":["id":1,"name":"admin"]],"links":"first":"http:\/\/localhost\/api\/admin\/users?page=1","last":"http:\/\/localhost\/api\/admin\/users?page=1","prev":null,"next":null,"meta":"current_page":1,"from":1,"last_page":1,"path":"http:\/\/localhost\/api\/admin\/users","per_page":15,"to":1,"total":1"
    #callback: null
    #encodingOptions: 0
    +headers: Symfony\Component\HttpFoundation\ResponseHeaderBag #1220
      #computedCacheControl: array:2 [
        "no-cache" => true
        "private" => true
      ]
      #cookies: []
      #headerNames: array:5 [
        "cache-control" => "Cache-Control"
        "date" => "Date"
        "content-type" => "Content-Type"
        "x-ratelimit-limit" => "X-RateLimit-Limit"
        "x-ratelimit-remaining" => "X-RateLimit-Remaining"
      ]
      #headers: array:5 [
        "cache-control" => array:1 [
          0 => "no-cache, private"
        ]
        "date" => array:1 [
          0 => "Mon, 22 Jan 2018 13:54:31 GMT"
        ]
        "content-type" => array:1 [
          0 => "application/json"
        ]
        "x-ratelimit-limit" => array:1 [
          0 => 60
        ]
        "x-ratelimit-remaining" => array:1 [
          0 => 59
        ]
      ]
      #cacheControl: []
    
    #content: ""data":["id":1,"name":"Watson Cole","email":"ralph.mayert@example.com","role":["id":1,"name":"admin"]],"links":"first":"http:\/\/localhost\/api\/admin\/users?page=1","last":"http:\/\/localhost\/api\/admin\/users?page=1","prev":null,"next":null,"meta":"current_page":1,"from":1,"last_page":1,"path":"http:\/\/localhost\/api\/admin\/users","per_page":15,"to":1,"total":1"
    #version: "1.1"
    #statusCode: 200
    #statusText: "OK"
    #charset: null
    +original: array:3 [
      "data" => Illuminate\Support\Collection #1218
        #items: array:1 [
          0 => App\Http\Resources\User #1585
            +resource: App\User #1345
              #fillable: array:3 [
                0 => "name"
                1 => "email"
                2 => "password"
              ]
              #hidden: array:2 [
                0 => "password"
                1 => "remember_token"
              ]
              #connection: "sqlite"
              #table: null
              #primaryKey: "id"
              #keyType: "int"
              +incrementing: true
              #with: []
              #withCount: []
              #perPage: 15
              +exists: true
              +wasRecentlyCreated: false
              #attributes: array:7 [
                "id" => "1"
                "name" => "Watson Cole"
                "email" => "ralph.mayert@example.com"
                "password" => "$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm"
                "remember_token" => "dIKErDUxJU"
                "created_at" => "2018-01-22 13:54:31"
                "updated_at" => "2018-01-22 13:54:31"
              ]
              #original: array:7 [
                "id" => "1"
                "name" => "Watson Cole"
                "email" => "ralph.mayert@example.com"
                "password" => "$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm"
                "remember_token" => "dIKErDUxJU"
                "created_at" => "2018-01-22 13:54:31"
                "updated_at" => "2018-01-22 13:54:31"
              ]
              #changes: []
              #casts: []
              #dates: []
              #dateFormat: null
              #appends: []
              #dispatchesEvents: []
              #observables: []
              #relations: array:1 [
                "role" => Illuminate\Database\Eloquent\Collection #1214
                  #items: array:1 [
                    0 => App\Models\Role #1456
                      #fillable: array:4 [
                        0 => "id"
                        1 => "name"
                        2 => "display_name"
                        3 => "description"
                      ]
                      #table: "roles"
                      #connection: "sqlite"
                      #primaryKey: "id"
                      #keyType: "int"
                      +incrementing: true
                      #with: []
                      #withCount: []
                      #perPage: 15
                      +exists: true
                      +wasRecentlyCreated: false
                      #attributes: array:6 [
                        "id" => "1"
                        "name" => "admin"
                        "display_name" => "Raphael Schuster V"
                        "description" => "Myles Wehner"
                        "created_at" => "2018-01-22 13:54:31"
                        "updated_at" => "2018-01-22 13:54:31"
                      ]
                      #original: array:8 [
                        "id" => "1"
                        "name" => "admin"
                        "display_name" => "Raphael Schuster V"
                        "description" => "Myles Wehner"
                        "created_at" => "2018-01-22 13:54:31"
                        "updated_at" => "2018-01-22 13:54:31"
                        "pivot_user_id" => "1"
                        "pivot_role_id" => "1"
                      ]
                      #changes: []
                      #casts: []
                      #dates: []
                      #dateFormat: null
                      #appends: []
                      #dispatchesEvents: []
                      #observables: []
                      #relations: array:1 [
                        "pivot" => Illuminate\Database\Eloquent\Relations\Pivot #1344
                          +pivotParent: App\User #1216
                            #fillable: array:3 [
                              0 => "name"
                              1 => "email"
                              2 => "password"
                            ]
                            #hidden: array:2 [
                              0 => "password"
                              1 => "remember_token"
                            ]
                            #connection: null
                            #table: null
                            #primaryKey: "id"
                            #keyType: "int"
                            +incrementing: true
                            #with: []
                            #withCount: []
                            #perPage: 15
                            +exists: false
                            +wasRecentlyCreated: false
                            #attributes: []
                            #original: []
                            #changes: []
                            #casts: []
                            #dates: []
                            #dateFormat: null
                            #appends: []
                            #dispatchesEvents: []
                            #observables: []
                            #relations: []
                            #touches: []
                            +timestamps: true
                            #visible: []
                            #guarded: array:1 [
                              0 => "*"
                            ]
                            #rememberTokenName: "remember_token"
                            #accessToken: null
                          
                          #foreignKey: "user_id"
                          #relatedKey: "role_id"
                          #guarded: []
                          #connection: null
                          #table: "role_user"
                          #primaryKey: "id"
                          #keyType: "int"
                          +incrementing: true
                          #with: []
                          #withCount: []
                          #perPage: 15
                          +exists: true
                          +wasRecentlyCreated: false
                          #attributes: array:2 [
                            "user_id" => "1"
                            "role_id" => "1"
                          ]
                          #original: array:2 [
                            "user_id" => "1"
                            "role_id" => "1"
                          ]
                          #changes: []
                          #casts: []
                          #dates: []
                          #dateFormat: null
                          #appends: []
                          #dispatchesEvents: []
                          #observables: []
                          #relations: []
                          #touches: []
                          +timestamps: false
                          #hidden: []
                          #visible: []
                          #fillable: []
                        
                      ]
                      #touches: []
                      +timestamps: true
                      #hidden: []
                      #visible: []
                      #guarded: array:1 [
                        0 => "*"
                      ]
                    
                  ]
                
              ]
              #touches: []
              +timestamps: true
              #visible: []
              #guarded: array:1 [
                0 => "*"
              ]
              #rememberTokenName: "remember_token"
              #accessToken: null
            
            +with: []
            +additional: []
          
        ]
      
      "links" => array:4 [
        "first" => "http://localhost/api/admin/users?page=1"
        "last" => "http://localhost/api/admin/users?page=1"
        "prev" => null
        "next" => null
      ]
      "meta" => array:7 [
        "current_page" => 1
        "from" => 1
        "last_page" => 1
        "path" => "http://localhost/api/admin/users"
        "per_page" => 15
        "to" => 1
        "total" => 1
      ]
    ]
    +exception: null
  

如何获取 json 响应而不是集合?

【问题讨论】:

【参考方案1】:

要获取 JSON,您可以这样做:

->baseResponse->getData()

或者你可以这样做:

->original->toJson()

【讨论】:

baseResponse->getData() 返回 json,但是如何使用 assertJsonCount。我收到此错误:BadMethodCallException:方法 assertJsonCount 不存在。 $users = createUserAs($this->adminRole , 3); $result = $this->get('api/admin/users'); $result->assertStatus(200); $result->baseResponse->getData()->assertJsonCount(count($users)); @JaysonVinicius 为什么要在 JSON 上运行该方法?只需像以前一样使用此响应即可。【参考方案2】:

这适用于我的测试:

$users = createUserAs($this->adminRole , 3);

$result = $this->get('api/admin/users')
    ->assertStatus(200)
    ->baseResponse->getData()->data;

$this->assertEquals(count($users), count($result));

【讨论】:

【参考方案3】:

resource 基类有 resolve 方法可以在测试中将资源转换为数组

/** @test */
    public function it_will_ensures_resource_return_response()
    
        factory(Model::class, 2)->create();

        $collect = ModelResource::collection(Model::all())->resolve();

        $this->assertCount(2, $collect);
    

【讨论】:

以上是关于phpunit 测试资源 laravel 5.5 返回集合而不是 json的主要内容,如果未能解决你的问题,请参考以下文章

如何在 laravel 5.5 中使用 phpunit 测试中间件?

如何使用内存数据库中的 sqlite 在 laravel 5.5 中运行单元测试

如何在 laravel 5.5 中运行 phpunit

在 Laravel 5.5 中测试授权策略时遇到问题

Laravel 5.5 中 PHP 单元测试中的类验证器错误

Laravel 5.5:PHPUnit(带覆盖)不喜欢来自多个文件的路由并抛出“尚未设置外观根”。没有报道它是绿色的