如果存在使用PHPUnit通过测试执行的在Controller中设置Session的过程,则会发出错误并且将失败

时间:2019-07-28 07:19:51

标签: php phpunit laravel-5.8

如果存在使用PHPUnit通过测试执行的在Controller中设置Session的过程,则将发出错误“未按要求设置Session store”,并且它将失败。

PHP 7.1 幼虫5.8 PHPunit 7.5

public function auth(Request $request)
{
    $email = $request->input('id');
    $password = $request->input('password');

    // I intend to succeed..
    //$Client = App::make('Client');
    //$res = $Client->authenticate($email, $password);
    $res = true;
    if ($res) {
      $token = "sampletoken";
      $request->session()->put('Authorization', $token);
      return redirect()
        ->intended('/list');
    }
    return redirect('/login');
}

<?php

namespace Tests\Feature;

use Illuminate\Http\Request;
use App\Http\Controllers\LoginController;
use Tests\TestCase;
use Mockery;

class LoginControllerTest extends TestCase
{
  public function testAuth()
  {
    $request = new Request();
    $request->merge([
        "id" => "test_id",
        "password" => "test_pass"
    ]);
    $controller = new LoginController();
    $response = $controller->auth($request);
    $this->assertEquals(preg_match('/\/list/', $response->getTargetUrl()), 1);
  }
}
1) Tests\Feature\LoginControllerTest::testAuth
RuntimeException: Session store not set on request

请告诉我解决方法。

2 个答案:

答案 0 :(得分:0)

在测试setUp方法中,您可以在请求上设置会话,并告诉它使用array驱动程序,以使其不持久:

$this->app['request']->setSession($this->app['session']->driver('array'));

答案 1 :(得分:0)

@atymic谢谢!我这样写,但是出现以下错误。 我还需要定义什么吗?

public function setUp() : void
{
    parent::setUp();
    $this->app['request']->setSession($this->app['session']->driver('array'));
}
TypeError: Argument 1 passed to Symfony\Component\HttpFoundation\Request::setSession() must be an instance of Symfony\Component\HttpFoundation\Session\SessionInterface, instance of Illuminate\Session\Store given