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

时间:2018-09-06 20:08:17

标签: php laravel phpunit

我遇到了一个似乎无法解决的问题。我正在运行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": "nlangosh@example.net",
    "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' => 'nlangosh@example.net'
    'active' => 1
    'timezone' => null
    'settings' => null
).
--- Expected
+++ Actual
@@ @@
         (
         )

-    [id] => 1
-    [subscription_id] => 
-    [name] => Ottilie Marvin
-    [email] => nlangosh@example.net
-    [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());

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

1 个答案:

答案 0 :(得分:0)

我发现了我的问题。通过遵循本文,我为资源添加了一些功能。 https://hackernoon.com/hiding-api-fields-dynamically-laravel-5-5-82744f1dd15a

即使它可以在应用程序中运行,测试也会在响应中返回一个空的数据字段。我恢复了这一点,将找到另一种过滤数据的方法。