Laravel Unit Testing Dependency Injection Laravel Unit Testing Dependency Injection laravel laravel

Laravel Unit Testing Dependency Injection


I figured it out. Here is the updated class.

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

Thanks to @edcs for guiding me in the right direction.You need to use a setUp function and not __construct as the app instance hasn't been created yet.


If you want to use __construct you have to use the same constructor of PHPUnit\Framework\TestCase and remember to call the parent method if you don't want to break anything

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

However the proper way would be to use the method setUpBeforeClass() if you want to execute your init code once or setUp() if you want to execute the init code before each test contained in your class.Check PHPUnit documentation for more details.