【问题标题】:If there is a process to set Session in Controller executed by test using PHPUnit, error will be issued and it will fail如果使用 PHPUnit 测试执行的 Controller 中有设置 Session 的进程,会报错,会失败
【发布时间】:2019-07-28 07:19:51
【问题描述】:

如果使用 PHPUnit 测试执行的 Controller 中设置 Session 的过程,则会发出错误“Session store not set on request”,并且会失败。

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

请告诉我解决方法。

【问题讨论】:

    标签: php phpunit laravel-5.8


    【解决方案1】:

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

    $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 给定
    • 自从(我认为)Laravel 5.5 之后,它不再被称为 setSession 而是 setLaravelSession
    猜你喜欢
    • 2017-03-18
    • 1970-01-01
    • 2011-04-20
    • 2011-04-24
    • 1970-01-01
    • 1970-01-01
    • 2014-01-05
    • 1970-01-01
    • 2012-12-07
    相关资源
    最近更新 更多