Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Herchelle's avatar

PhpUnit and Laravel 5.4 how to mock Session data during a test

I'm testing a class in laravel 5.4 with phpunit that uses the session to get data. Retrieving the session data works when accessing it directly when the app is running aka "session('consumer')" returns a value, however when i try to test a function that uses the session, I get the below error:

ReflectionException: Class session does not exist

Can someone please shed some light on how to accomplish setting session data during a test.

I have tried using:

$this->session()->put([$array_value]) but get an error "class session does not exist on class_im_testing"

Thanks in advance for your help!

public function test_get_user()
{
    $mockUser =  [
        'id' => 'cf442564-d076-4198-beb5-edef5aa51a69',
        'name' => 'John Doe',
        'fname' => 'John',
        'lname' => 'Doe',  
    ];

    session->put('consumer', [
        'id' => 'cf442564-d076-4198-beb5-edef5aa51a69',
        'name' => 'John Doe',
        'fname' => 'John',
        'lname' => 'Doe',  
    ]);

    $user = $this->repo->getUser();

    $this->assertEqual($user, $mockUser);
}


public function getUser()
{
   $user = new User(session('consumer'));
   return $user;
}
0 likes
2 replies
Web Confection's avatar

@Herchelle You should be passing in the value of session to getUser as a parameter.

Secondly, why test that method? It is incredibly simple and the underlying code will have been tested as part of the framework. You are testing for-the-sake-of-testing.

Good luck

1 like
Herchelle's avatar
Herchelle
OP
Best Answer
Level 1

@CJJ I solved the issue by using $this->withSession([...]). I was also extending the wrong TestCase class. By extending the correct TestCase class, I get the method $this->withSession.

That is not the full method I'm testing, and also have other method where I need to mock the session in order to make a request to DB.

Thank You

1 like

Please or to participate in this conversation.