Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 201
user1012181 Avatar asked Oct 28 '25 15:10

user1012181


1 Answers

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
        ]);
}
like image 86
samlev Avatar answered Oct 30 '25 07:10

samlev