【问题标题】:Testing Laravel API resources with dependency injections and custom requests使用依赖注入和自定义请求测试 Laravel API 资源
【发布时间】:2018-10-19 01:14:19
【问题描述】:

类型提示的路由参数在从测试中调用时不会实例化。

我有一个 Laravel API 资源Route::apiResource('users', 'Api\UserController');

这是我在控制器中的更新方法:

public function update(UpdateUserRequest $request, User $user)
{
    //
}

UpdateUserRequest 内部:

public function rules()
{
    dd($this->route("user"));
}

如果我从 Postman 调用此端点,我会返回完整的 user 对象。但是,如果我从测试中调用它:

    $response = $this->actingAs($this->user)->
        json('POST', '/api/users/'.$this->user->id, [
            '_method' => 'PUT',
            'data' => [
                // ...
            ]
        ]);

我只得到字符串“1”,而不是实例化的用户对象。

【问题讨论】:

    标签: laravel dependency-injection phpunit laravel-5.2 inversion-of-control


    【解决方案1】:

    嗯,有一件事奏效了,我不知道这是正确的还是“Laravel”的做事方式是强制在自定义请求构造函数中实例化模型,并在测试中绑定实例:

    在 UpdateUserRequest 中:

    private $user;
    
    public function __construct(User $user)
    {
        $this->user = $user;
    }
    

    在测试中:

    $this->user = factory(\App\Models\User::class)->create();
    $this->app->instance(\App\Models\User::class, $this->user);
    

    【讨论】:

      【解决方案2】:

      这可能是由您的测试用例使用的\Illuminate\Foundation\Testing\WithoutMiddleware trait 引起的。

      对于后代,如果有人遇到这种情况,路由模型绑定由\Illuminate\Routing\MiddlewareSubstituteBindings 中间件执行。因此,WithoutMiddleware trait 会阻止它运行。

      基本的 Laravel 测试用例通过 /Illuminate/Foundation/Testing/WithoutMiddleware 提供了一个未记录的 withoutMiddleware() 方法,您可以使用它来解决这个问题,但是值得注意的是,Laravel 的首席开发人员 Taylor Otwell,recommends 使用所有测试尽可能激活中间件。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-05-17
        • 2017-04-01
        • 2018-01-27
        • 1970-01-01
        • 1970-01-01
        • 2021-06-19
        • 1970-01-01
        相关资源
        最近更新 更多