Search code examples
laravellaravel-dusk

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


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 ?


Solution

  • 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);
    }