-1

我正在使用基于帐户模型的 Laravel 构建多租户 API,我通过在所有租户模型上使用特征(AccountScoped)来确定请求阅读器“帐户”正在使用的租户,一切都在邮递员上工作,但是为什么要测试标题在特质上是不可访问的。

AccountScoped (特征)

trait AccountScoped
{
protected static function bootAccountScoped()
{
    $account_id = request()->header('Account');
    dd($account_id);
    if (empty($account_id)) {
        return;
    }

    static::creating(function (Model $model) use ($account_id) {
        $model->account_id = $account_id;
    });

    static::addGlobalScope('byAccount', function (Builder $builder) use ($account_id) {
        $builder->where('account_id', '=', $account_id);
    });
}
}

测试方法:

public function testActionIndexInController()
{
    $categories = Category::where('account_id',$this->account->id)->get()->toJSON();
    $response = $this->actingAs($this->user, 'api')
                    ->withHeader('Account',$this->account->id)
                    ->get(route('categories.index'));

    $response->assertStatus(200)->assertSee($categories);
}

* $this->user 是一个带有 Accounts 的 User 实例模型,$this->account 是一个与所选用户相关的 Account 实例

但是当我运行测试时,我在 $account_id 测试返回上得到空值

当我通过邮递员提出相同的请求时,值就在那里 邮递员返回

4

1 回答 1

0

如果您使用的是 jwt,您可以在测试模式下使用此代码设置请求

if (env('APP_ENV') === 'testing') {
     JWTAuth::setRequest($request);
}

否则,您需要使用 Illuminate\Http\Request 设置请求;另外,您可以尝试使用此代码来获取标题

\Illuminate\Support\Facades\Request::instance()->headers->get('Account')
于 2019-11-24T22:05:19.693 回答