Home > other >  Laravel PhpUnit Dependency Injection
Laravel PhpUnit Dependency Injection

Time:12-12

I'm using Dependency injection to call custom services in Laravel and it works fine. But when i inject those dependencies into my Phpunit test case classes using interfaces, i receive the following error:

Target [App\Services\Interfaces\CarServiceInterface] is not instantiable.

although the interface has been bound to the target concrete class in the provider correctly.
i've used different styles like injecting through the __construct() method, inject to test method or even calling the app() method, but none of them works.
What is the correct way to do this?

CodePudding user response:

You need to write your test in feature section as feature tests are inherited from laravel base test case and they have CreatesApplication trait. Refer to here

After that, you can simply get your concrete class instance using app('Your abstract class namespace ') method or $this->app->make('Your abstract class namespace ') in your test.

CodePudding user response:

Obviously the wrong test approach. Why do you need DI in a test class?! In a test class you have to prepare and maybe bind/mock the required classes. And then test your code.

Second part the error says the class are not bind correcly in spite of your assumption.

BTW, if you think I've missed sth, and you need DI, use singleton method.

$this->app->singleton(CarServiceInterface::class, fn () => $exampleInstance);

Now you can use container to access your interface like this without DI error:

$this->app[CarServiceInterface::class]
//or
$this->app->make(CarServiceInterface::class)
//or
app(CarServiceInterface::class)
  • Related