Laravel PHPUnit test authenticated routes
Log users in when running tests using Laravel Passport
Writing tests is always important to maintain the quality of your codebase. Most Laravel APIs will have authenticated routes, which only logged-in users can access or users with certain roles etc. To write tests for these routes you will need to mock logins in your test. I will show how you can achieve this with minimal fuss.
You need to sign in a different user for each test, so before each request, you send you could create a user and sign them in, but it will get very repetitive if you have any more than a few tests in your codebase.
Let’s make this as easy as possible. First, create a new trait in your tests folder:
Then use the trait in your TestCase.php
class:
use CreatesApplication, InteractsWithUsers;
Now you should be able to use the setUpUser()
method in any test.
public function test_hello_world()
{
$this->setUpUser(); $response = $this->get(route('some-route')); $response->assertStatus(200);
}
All you need to do is call a method to sign in a user at the start of your test and let the trait create a new user and mock log this user in using Laravel Passport. Now you can test your API is correctly throwing ‘Unathorized’ and ‘Forbidden’ errors when your user is not set up correctly. Thanks for reading!