Laravel单元测试-向请求添加cookie?

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

我想发送带有JSON POST的Cookie:

public function testAccessCookie()
{
    $response = $this->json('POST', route('publications'))->withCookie(Cookie::create('test'));
    //some asserts
}

发布路线具有一些中间件:

public function handle($request, Closure $next)
{
    Log::debug('cookie', [$request->cookies]);

    //cookie validation

    return $next($request);
}

但是运行testAccessCookie()时,日志中有[null]。没有附加Cookie。

怎么了?

真正的(浏览器中的)请求没有这样的问题。

phpunit laravel-5.7
2个回答
3
投票

您可以向测试中的通话添加cookie:

$cookies = ['test' => 'value'];

$response = $this->call('POST', route('publications'), [], $cookies);

请参见https://laravel.com/api/5.4/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.html#method_call

但是您会遇到Cookie加密问题。您可以使用以下方法暂时禁用Cookie:

use Illuminate\Cookie\Middleware\EncryptCookies;

/**
 * @param array|string $cookies
 * @return $this
 */
protected function disableCookiesEncryption($name)
{
    $this->app->resolving(EncryptCookies::class,
        function ($object) use ($name)
        {
          $object->disableFor($name);
        });

    return $this;
}

在测试开始时添加$this->disableCookiesEncryption('test');

您可能需要添加标题以指定json响应。


0
投票

这应该在最新版本(Laravel 6)中起作用:

任一:

$this->disableCookieEncryption();

或:

$cookies = ['test' => encrypt('value', false)];

$response = $this->call('POST', route('publications'), [], $cookies);
© www.soinside.com 2019 - 2024. All rights reserved.