user1012181 user1012181 - 20 days ago 5
PHP Question

User Authentication in Unit Testing Laravel 5.1

I'm a bit confused about the unit testing in Laravel 5.1.

I want to test the updating of settings from a user account. I'm using

phpunit
for testing.

This is my test case.

/** @test */
public function it_updates_personal_details(){

$this->withoutMiddleware();
$this->visit('/account/settings')
->post('/account/settings', ["firstname"=>"RingoUpdated", 'lastname'=>"RingyUpdated", "username"=>"ringo", "bio"=>"My Personal Information", "facebook"=>"myFbUsername", "twitter"=>"myTwUsername", ])
->seeJson([
"signup"=>true
]);
}


But in my controller, I'm using
Auth::id()
to get the current logged in user's
id
. How can I mock this in
Laravel
5.1 ?

Answer

The simplest way is to make use of Mockery in the Facade:

public function it_updates_personal_details(){
    Auth::shouldReceive('id')->andReturn(1);

    $this->withoutMiddleware();
    $this->visit('/account/settings')
        ->post('/account/settings', ["firstname"=>"RingoUpdated", 'lastname'=>"RingyUpdated", "username"=>"ringo", "bio"=>"My Personal Information", "facebook"=>"myFbUsername", "twitter"=>"myTwUsername", ])
        ->seeJson([
            "signup"=>true
        ]);
}