Reputation: 73
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;
}
Upvotes: 7
Views: 9868
Reputation: 40673
Laravel offers a lot of methods to help with testing but in order to make use of them you need to ensure you are using the correct class.
If you're using the default boilerplate you get a TestCase
class. This is the class you need to extend in order to get method such as $this->withSession
.
This is because the test case extends the Framework TestCase
class which in turn includes many traits, among them is the the trait InteractsWithSession
which is the trait which actually offers the method withSession
.
In addition the Laravel TestCase also extends the PhpUnit test case so you still have access to all PhpUnit assertions.
Upvotes: 8