2016-11-17 262 views
5

我正在嘗試編寫購物車的測試類。以下是我有:Laravel單元測試依賴注入

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 

我有我的購物類被在多個不同的控制器就好解決了。

爲什麼Laravel無法在測試中解決它?

我指的是this post,但仍然沒有任何運氣。

+0

您可以發佈'App \ Classes \ Billing \ ShoppingCart'的構造函數嗎? – edcs

+0

@edcs當然可以。這是班級。 http://pastebin.com/bPRpmtnH –

+2

很酷 - 謝謝!您可以嘗試使用'$ this-> app-> make('App \ Classes \ Billing \ ShoppingCart');'因爲所有的Laravel測試都有一個可用的應用程序實例作爲屬性。 – edcs

回答

8

我想通了。這是更新的類。

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實例。