samedi 22 août 2020

How to mock a given method of Laravel Auth facade

I want to test that the Auth facade, when createUserProivder() method is called, returns my user provider.

The problem is that with the following code, with the commented out part, the AuthManager is still the original, not the mock. With the uncommented part, I get an error: Mockery\Exception\BadMethodCallException : Method Mockery_2_Illuminate_Auth_AuthManager::validate() does not exist on this mock object

I don't know how to test it.

I want to test a custom guard behavior, that calls the UserProvider when Guard's validated() method is called, and for that reason I need to mock the Auth facade, because it is the one that returns the User Provider.

public function testUserIsAuthenticatedWhenUserProviderFindsCredentialsMatch()
    {
        $userId = Uuid::uuid();
        $user = new User($userId);
        $userProvider = new UserProvider($user);

//        $this->partialMock(AuthManager::class, function ($mock) use ($userProvider) {
//            $mock->shouldReceive('createUserProvider')
//                ->once()
//                ->andReturn($userProvider);
//        });

        Auth::shouldReceive('createUserProvider')
           ->once()
           ->andReturn($userProvider);

        $result = $this->app['auth']->validate(['dummy' => 123]);

Method to test:

/**
     * @param array $credentials
     * @return bool
     */
    public function validate(array $credentials = []): bool
    {
        $this->user = $this->provider->retrieveByCredentials($credentials);

        return (bool)$this->user;
    }

Service provider:

class LaravelServiceProvider extends AuthServiceProvider
{
    /**
     * Register any application authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        Auth::extend(
            'jwt',
            function ($app, $name, array $config) {
                $moduleConfig = $app['config'];

                return new JWTAuthGuard(
                    Auth::createUserProvider($config['provider']),
                    $this->app['request'],
                    new JWTHelper()
                );
            }
        );
    }
}

Aucun commentaire:

Enregistrer un commentaire