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

mstdmstd's avatar

How to make authorization with php unit ?

Hello, In my laravel 5.6 application I need to use php unit tests, like in file tests/Feature/VotesAdminCrudTest.php I do:

<?php

namespace Tests\Feature;

use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;
use App\Settings;
use App\User;


class VotesAdminCrudTest extends TestCase
{
    public function testVotesListing()
    {
        $settingsArray              = Settings::getSettingsList( ['site_name', 'site_heading', 'site_subheading'], true);
        $site_name= $settingsArray['site_name' ] ? $settingsArray['site_name' ] : '';
        $logged_user_id = 5;
        $loggedUser= User::find($logged_user_id);

//        $this->actingAs($loggedUser);
        $response = $this->get('/admin/votes');
        $response->assertStatus(200);
//        $response->assertTitle($site_name);   
        
        $response->assertSee('Votes Listing');
        
    }
}

But running command :

$ vendor/bin/phpunit

I got error:

Expected status code 200 but received 302.
Failed asserting that false is true.

As my /admin/votes page needs authorization, looks like that is the reason, but I do not know how to make authorization in my case? Googling I found actingAs method, bit looks like response object has not it? Which is the right way?

  1. has $response object assertTitle method, I used with dusk, or subtitution of it ?

Thanks!

0 likes
3 replies
Tray2's avatar

You can put this in your TestCase.php

protected function signIn($user = null)
    {
        $user = $user ?: factory(User::class)->create();
        $this->actingAs($user);
        return $this;
    }

Then you use it like this in your tests.

$this->signIn();

You can pass a user to the method if you want a certain name on the user.

1 like
tykus's avatar
tykus
Best Answer
Level 104

There is an actingAs() helper method which you can chain also:

$response = $this->actingAs($loggedUser)->get('/admin/votes');
1 like
mstdmstd's avatar

Thank you! Also I have 2 questions :

  1. If response object has assertTitle(I got error trying to call it) method or if there is some other way to check text in Tag?

  2. If I got error in line like

        $response->assertSee('Non existing text');

in console I see long text(html-output of my url) and message text at the end of the output:

</footer></html>\n
' contains "Non existing text".

This long text oupput seems very unconvinient. If there is a way to manipulate/cut it?

Please or to participate in this conversation.