How to test a class with DI-ed facade in Laravel

383 Views Asked by At

PHP 8.1.1 / Laravel 9

I had Config:get('keycloak.employees_group_id') in my task, and Config::shouldReceive('get')->with('keycloak.employees_group_id')->andReturn('fake-id') in my test which worked NP.

Then I wanted to use DI (dependency injection) approach and my task changed to the following.

Task

class FetchGroupMembers implements TaskHandler
{
    public function __construct(
        private Config $config,
        ...
    ) {}

    public function handle(ExternalTask $task): array
    {
        $employeesGroupId = $this->config->get('keycloak.employees_group_id');

        ...
    }
}

Test

How do I test this now?

I have tried the following, but none of them work.

class FetchGroupMembersTest extends TestCase
{
    private MockInterface|Config $config;
    ...

    public function setUp(): void
    {
        parent::setUp();

        // Option 1
        $this->config = Mockery::mock(Config::class);
        // Option 2
        $this->config = Mockery::mock(Config::class, function (MockInterface $mock) {
            $mock
                ->shouldReceive('get')
                ->with('keycloak.employees_group_id')
                ->andReturn('fake-id')
        });
        // Option 3
        $this->config = $this->mock(Config::class)
        // Option 4
        $this->config = $this->mock('alias:' . Config::class);
        ...
    }

    public function testFiltersOutUsersWithoutGeckoId(): void
    {
        $employeesGroupId = 'fake-id';
        ...

        // Options 1, 3, 4
        $this->config
            ->shouldReceive('get')
            ->with('keycloak.employees_group_id')
            ->once()
            ->andReturn($employeesGroupId);
        ...

        $fetchGroupMembersHandler = new FetchGroupMembers(
            $this->config,
            ...
        );
        $variables = $fetchGroupMembersHandler->handle($this->task);
        ...
    }
}
0

There are 0 best solutions below