Search code examples
laravelunit-testingcodeceptionlaravel-authentication

How to mock authentication user on unit tests with Codeception in Laravel 5?


I have to convert my unit tests to codeception. I need to use loginWithFakeUser() function from this article - How to mock authentication user on unit test in Laravel?

public function loginWithFakeUser() {
    $user = new User([
        'id' => 1,
        'name' => 'yish'
    ]);
    $this->be($user);
}

How can I use the $this->be() when my class is already extending \Codeception\Test\Unit? I don't know what should I use .. or how to use properly. Putting the function loginWithFakeUser() inside this:

use Illuminate\Foundation\Testing\Concerns\InteractsWithAuthentication;
use Illuminate\Foundation\Testing\Concerns\InteractsWithSession;

class AdminTest extends \Codeception\Test\Unit {
    use InteractsWithAuthentication;
    use InteractsWithSession;
}

Gives me an error:

[ErrorException] Undefined property: AdminTest::$app

I'm not sure how can I set the $app variable. Please help me. Thanks a lot!


Solution

  • I was able to solve this by mocking the Auth class.

    $oUser = new User([
        'id' => 1,
        'name' => 'yish'
    ]);
    
    Auth::shouldReceive('check')->once()->andReturn(true);
    Auth::shouldReceive('user')->once()->andReturn($oUser);
    

    Where in my actual code it uses it as:

    if(Auth::check() === true) {
        $sName = Auth::user()->name;
    }