簡體   English   中英

Laravel單元測試依賴注入

[英]Laravel Unit Testing Dependency Injection

我正在嘗試為購物車編寫測試類。 這是我有的:

ShoppingCartTest.php

class ShoppingCartTest extends TestCase {

    use DatabaseTransactions;

    protected $shoppingCart;

    public function __construct() {
        $this->shoppingCart = resolve('App\Classes\Billing\ShoppingCart');
    }

    /** @test */
    public function a_product_can_be_added_to_and_retrieved_from_the_shopping_cart() {

        // just a placeholder at the moment
        $this->assertTrue(true);
    }

}

但是,當我運行phpunit時,似乎Laravel無法解析我的ShoppingCartClass。

這是錯誤:

Fatal error: Uncaught exception 'Illuminate\Contracts\Container\BindingResolutionException'
with message 'Unresolvable dependency resolving
[Parameter #0 [ <required> $app ]] in class Illuminate\Support\Manager'
in C:\Development Server\EasyPHP-Devserver-16.1\eds-www\nrponline\vendor\laravel\framework\src\Illuminate\Container\Container.php:850

我讓我的ShoppingCart類在很多不同的控制器中得到解決。

為什么Laravel在測試期間無法解決它?

我也提到了這篇文章 ,但仍然沒有任何運氣。

我想到了。 這是更新的課程。

class ShoppingCartTest extends TestCase {

    use DatabaseTransactions;

    protected $shoppingCart;

    public function setUp() {

        parent::setUp();

        $this->shoppingCart = $this->app->make('App\Classes\Billing\ShoppingCart');
    }

    /** @test */
    public function a_product_can_be_added_to_and_retrieved_from_the_shopping_cart() {

        // just a placeholder at the moment
        $this->assertTrue(true);
    }

}

感謝@edcs指導我正確的方向。 您需要使用setUp函數而不是__construct因為尚未創建app實例。

如果你想使用__construct你必須使用相同的PHPUnit\\Framework\\TestCase構造函數,如果你不想破壞任何東西,請記得調用父方法

class MyTest extends TestCase
{
    public function __construct($name = null, array $data = [], $dataName = '')
    {
        parent::__construct($name, $data, $dataName);

        // my init code
    }
}

但是,正確的方法是使用setUpBeforeClass()方法setUpBeforeClass()如果要執行一次初始化代碼)或setUp()如果要在類中包含的每個測試之前執行初始化代碼)。 查看PHPUnit文檔以獲取更多詳細信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM