Laravel Testing Service Injection Error

To start with the output, I get this error:

[ErrorException] Argument 1 passed to SomeValidatorTest::__construct() must be an instance of App\Services\Validators\SomeValidator, none given, called in ....vendor/phpunit/phpunit/src/Framework/TestSuite.php on line 475 and defined 

In a Laravel application, I have a script called "SomeValidator.php" that looks like this:

 <?php namespace App\Services\Validators; use App\Services\SomeDependency; class SomeValidator implements ValidatorInterface { public function __construct(SomeDependency $someDependency) { $this->dependency = $someDependency; } public function someMethod($uid) { return $this->someOtherMethod($uid); } } 

which works without errors.

Then the test script, SomeValidatorTest.php looks like this:

 <?php use App\Services\Validators\SomeValidator; class SomeValidatorTest extends TestCase { public function __construct(SomeValidator $validator) { $this->validator = $validator; } public function testBasicExample() { $result = $this->validator->doSomething(); } } 

The error appears only when the test script is run through. / vendor / bin / phpunit. It seems that the test class is initiated without the specified dependency and throws an error. Does anyone know how to fix this? Thanks in advance.

+4
source share
1 answer

You cannot inject classes into tests (as far as I know), given that they are not resolved automatically with laravel / phpUnit.

The right way is to make them through the laravel app facade. Your test script should look like this:

 <?php class SomeValidatorTest extends TestCase { public function __construct() { $this->validator = \App::make('App\Services\Validators\SomeValidator'); } public function testBasicExample() { $result = $this->validator->doSomething(); } } 

Source: http://laravel.com/docs/5.1/container

+5
source

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


All Articles