Home > Net >  Why I can't inject a class in a test case with dusk
Why I can't inject a class in a test case with dusk

Time:10-30

I am testing my laravel project with dusk.

I am trying to inject a dependency in a test like that :

....
class PasswordLostTest extends DuskTestCase
{
    private $passwordResetRepository;
    
    public function __construct(PasswordResetRepository $passwordResetRepository)
    {
        $this->passwordResetRepository = $passwordResetRepository;
    }
.....

When I run the test with php artisan dusk .\tests\Browser\PasswordLostTest.php, I have this error :

Fatal error: Uncaught ArgumentCountError: Too few arguments to function Tests\Browser\PasswordLostTest::__construct(), 0 passed in D:\Workspace\classified-ads-mpa\vendor\phpunit\phpunit\src\Framework\TestBuilder.php on line 138 and exactly 1 expected in D:\Workspace\classified-ads-mpa\tests\Browser\PasswordLostTest.php:20

What is the problem ? Is it because I am in a test script ?

CodePudding user response:

TestCases are not instantiated by the container. Secondly your app is not bootstrapped before setup has been called, the constructor is called first. Making your example technically impossible. Instead use resolve() or app()->make(), in the setup method to do what you want.

Your app is bootstrapped to the parent test cases setup, so calling parent::setUp(); is essential.

public function setUp()
{
    parent::setUp();
    $this->passwordResetRepository = resolve(PasswordResetRepository::class);
}

CodePudding user response:

Here is the solution :

public function setUp(): void
    {
        parent::setUp();
        $this->passwordResetRepository = resolve(PasswordResetRepository::class);
    }

WARNING : the void is mandatory. That's why it did not work !

Many thanks to mrhn who guided me for this problem !

  • Related