我正在使用依賴注入在 Laravel 中呼叫自定義服務,它作業正常。但是當我使用介面將這些依賴項注入到我的 Phpunit 測驗用例類中時,我收到以下錯誤:
目標 [App\Services\Interfaces\CarServiceInterface] 不可實體化。
盡管介面已正確系結到提供程式中的目標具體類。
我使用了不同的風格,比如通過__construct()方法注入、注入到測驗方法甚至呼叫app()方法,但它們都不起作用。
測驗檔案:
private $carService;
public function setUp(): void
{
parent::setUp();
$this->carService = app(CarServiceInterface::class);
}
提供者:
$this->app->bind(
App\Services\Interfaces\CarServiceInterface::class,
App\Services\CarService::class
);
這樣做的正確方法是什么?
uj5u.com熱心網友回復:
您需要在功能部分撰寫測驗,因為功能測驗是從 laravel 基本測驗用例繼承的,并且它們具有CreatesApplication特征。參考這里
之后,您可以簡單地使用app('Your abstract class namespace ')方法或$this->app->make('Your abstract class namespace ')在您的測驗中獲取您的具體類實體。
uj5u.com熱心網友回復:
顯然是錯誤的測驗方法。為什么在測驗類中需要 DI?!在測驗類中,您必須準備并系結/模擬所需的類。然后測驗你的代碼。
第二部分錯誤表明,盡管您做出了假設,但該類并未正確系結。
順便說一句,如果您認為我錯過了某些東西,并且您需要 DI、用途bind或singleton方法。
$this->app->bind(CarServiceInterface::class, fn () => $exampleInstance);
//or
$this->app->singleton(CarServiceInterface::class, fn () => $exampleInstance);
現在您可以使用容器來訪問您的界面,而不會出現 DI 錯誤:
$this->app[CarServiceInterface::class]
//or
$this->app->make(CarServiceInterface::class)
//or
app(CarServiceInterface::class)
uj5u.com熱心網友回復:
嗯,我終于找到了問題所在。盡管其他人給出的所有答案/建議也是正確的。
我的測驗用例類擴展了錯誤的 TestCase 命名空間。通過將其更改為App\TestCase它已修復。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/379989.html
