Laravel dependency injection into custom non-controller class fails in PHPUnit -
all.
for laravel project i'm working on, i've started use dependency injection in order mock classes in tests. however, i've found if try inject custom class no explicit parent, 2 things true:
- the dependency injection works correctly when running application
- the injection fails when running tests in phpunit
here sample code similar i'm using:
democontroller
// controller we're testing class democontroller extends controller { // injection , constructor private $helplayer1; public function __construct(helplayer1 $helplayer1) { $this->helplayer1 = $helplayer1; } ... // test function call public function testdeps() { $this->helplayer1->testlayer1(); } }
helperlayer1
// our first helper class class helperlayer1 { private $helplayer2; public function __construct(helplayer2 $helplayer2) { $this->helplayer2 = $helplayer2; } ... // testing function public function testlayer1() { // when called via route, dumps actual object // when called via test, returns null dd($this->helperlayer2); } }
helper1serviceprovider
class helper1serviceprovider extends serviceprovider { public function register() { $this->app->bind('helperlayer1', function() { return new helperlayer1(app::make('helperlayer2')); }); } [or] public function register() { $this->app->bind('helperlayer1', 'helperlayer1'); } }
helper2serviceprovider
class helper2serviceprovider extends serviceprovider { public function register() { $this->app->bind('helperlayer2', 'helperlayer2'); } }
i'm relatively new using di, i'm not entirely sure set-up correct, i'm @ loss.
any appreciated! thank you!
Comments
Post a Comment