F
F
FulgerX20072021-01-14 14:41:05
PHPUnit
FulgerX2007, 2021-01-14 14:41:05

How to test middleware with sessions?

There is a middleware

class Warning
{
    public function handle(Request $request, Closure $next)
    {
        if (!Route::is('warning') && $request->session()->exists('Warning')) {
            return redirect()->route('warning');
        }

        return $next($request);
    }
}


And there is a test for it:
class WarningTest extends TestCase
{
    public function testAcceptedWarning(): void
    {
        $request = new Request();
        
        $request->session()->put(['test' => true]);
        $middleware = new Warning();

        $response = $middleware->handle($request, static function () {
            return true;
        });
        self::assertTrue($response);
    }
}


When I run the test, I get an error:
RuntimeException : Session store not set on request.
on the line where the session is created
$request->session()->put(['test' => true]);
.

There is a line in phpunit.xml file How do I solve this session problem?
<server name="SESSION_DRIVER" value="array"/>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2021-01-22
@dlnsk

The point is that the Request object is created "empty". There is no Session object associated with the request. Searching for the error text in the source code will easily lead you to the place of the error, and from there it is easy to get to the initialization.
Maybe it's easier for you to use the method described in the documentation:
https://laravel.com/docs/5.8/http-tests#session-an...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question