使用Laravel资源测试API端点的问题

问题描述 投票:0回答:1

我遇到了一个我似乎无法修复的问题。我正在运行Laravel 5.6,我正在尝试向我的API发送一个返回资源集合的测试请求。但是,它返回一个空数组。

这在我的应用程序中工作,只是不确定它为什么不在测试中工作。我的代码如下。

我的控制器方法

public function index(Request $request)
{
    //
    if ($request->has('only'))
    {
        $columns = array_diff($request->query('only'), ['role']);
        $return = $request->query('only');

        return UserResource::collection(User::all($columns))->only($return);

    } else {
        return UserResource::collection(User::all());

    }

}

我的考试

/** @test */
public function getting_all_users_unauthenticated()
{

    // Without Authentication
    $this->getJson('/api/v1/users')
        ->assertStatus(401);

    // Create User and Auth Headers
    $this->createUserWithToken();

    // With Authencation
    $this->getJson('/api/v1/users')
        ->assertOk()
        ->assertJson(
            ['id' => $this->user->id,
             'subscription_id' => $this->user->subscription_id,
             'name' => $this->user->name,
             'email' => $this->user->email,
             'active' => $this->user->active,
             'timezone' => $this->user->timezone,
             'settings' => $this->user->settings 
        ]);

}

在api.php中路由

Route::group(['prefix' => 'v1', 'middleware' => 'auth:api'], function(){
    Route::apiResources([
        'users' => 'API\UserController'
    ]);
});

我在运行测试时得到了这个

Summary of non-successful tests:

Endpoints\Users
 ✘ Getting all users unauthenticated

Unable to find JSON: 

[{
    "id": 1,
    "subscription_id": null,
    "name": "Ottilie Marvin",
    "email": "[email protected]",
    "active": 1,
    "timezone": null,
    "settings": null
}]

within response JSON:

[[
    []
]].


Failed asserting that an array has the subset Array &0 (
    'id' => 1
    'subscription_id' => null
    'name' => 'Ottilie Marvin'
    'email' => '[email protected]'
    'active' => 1
    'timezone' => null
    'settings' => null
).
--- Expected
+++ Actual
@@ @@
         (
         )

-    [id] => 1
-    [subscription_id] => 
-    [name] => Ottilie Marvin
-    [email] => [email protected]
-    [active] => 1
-    [timezone] => 
-    [settings] => 
 )
/var/www/iosgen/iosgen_paper/vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestResponse.php:416
/var/www/iosgen/iosgen_paper/tests/Endpoints/UsersTest.php:33

但是,通过在控制器中执行此操作,我可以在不使用API​​资源的情况下使其工作

return response()->json(User::all());

有关资源为什么返回空数组的任何想法?

php laravel phpunit
1个回答
0
投票

我发现了我的问题。我按照这篇文章为资源添加了一些功能。 https://hackernoon.com/hiding-api-fields-dynamically-laravel-5-5-82744f1dd15a

即使它在应用程序中有效,测试也会在响应中返回一个空数据字段。我还原了这个,并将找到另一种过滤数据的方法。

© www.soinside.com 2019 - 2024. All rights reserved.