EDIT: Ugh, wtf, 2 years ago? How did this show up on the first page of my "no replies yet" section? o.Ô
If you really want to unit test the Middleware, you'll have to mock the request:
public function testExample()
{
$requestMock = \Mockery::mock(Illuminate\Http\Request::class);
$requestMock->shouldReceive('session')
// just return an anonymous dummy class that knows the has() method and
// returns true or false depending on our needs. Alternative would be
// to also mock the session and return the session mock.
->andReturn(new class
{
public function has(string $key)
{
return true; // or false, depends on what you want to test
}
});
$middleware = new RedirectIfAuthenticated;
$response = $middleware->handle($requestMock, function ($request) {
return 'I have not been redirected',
});
// If you want to test that no redirection has taken place
$this->assertEquals('I have not been redirected', $response);
// If you want to test that redirection did take place
$this->assertInstanceOf(\Illuminate\Http\RedirectResponse::class, $response);
}
On second thought, even the request mock is unnecessary and could be replaced by an anonymous class, since it is not typechecked in the middleware.
BUT
This seems overly complicated. Why not just make it an integration test instead of a unit test and use laravel's fluent api for testing requests?
public function testExample()
{
$this->withSession([env('SESSION_USER_ID') => '1234'])
->get('some/url')
->assertStatus(200); // no redirection
$this->withSession([])
->get('some/url')
->assertStatus(302); // redirection
}