Laravel Unit Testing Injection Dependency Injection

I am trying to write a test class for a shopping cart. Here is what I have:

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

However, when I run phpunit, it looks like Laravel cannot resolve my ShoppingCartClass.

Here is the error:

 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 

I have a ShoppingCart class that is allowed on a number of different controllers.

Why doesn't Laravel allow this during my tests?

I referenced this post , but still no luck.

+11
source share
2 answers

I get it. 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 the setUp function, not __construct , since the app instance has not yet been created.

+22
source

If you want to use __construct you must use the same PHPUnit\Framework\TestCase constructor 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 correct way would be to use the setUpBeforeClass() method if you want to execute the initialization code once, or setUp() if you want to execute the initialization code before each test contained in your class. Check out the PHPUnit documentation for more details.

0
source

Source: https://habr.com/ru/post/1259912/


All Articles