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

Tar*_*ych 3 phpunit laravel-5.7

我想用 json POST 发送一个 cookie:

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

发布路线有一些中间件:

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

    //cookie validation

    return $next($request);
}
Run Code Online (Sandbox Code Playgroud)

但是在运行时testAccessCookie()[null]里面有日志。没有附加饼干。

怎么了?

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

edl*_*uth 5

您可以在测试中向调用添加 cookie:

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

$response = $this->call('POST', route('publications'), [], $cookies);
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

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

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