[英]Laravel Testing Service Dependency Injection Error
To start from the conclusion, 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 Laravel app, I have a script called "SomeValidator.php" which looks like this: 在Laravel应用程序中,我有一个名为“SomeValidator.php”的脚本,如下所示:
<?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 runs without error. 哪个运行没有错误。
Then the test script, SomeValidatorTest.php looks like this: 然后测试脚本SomeValidatorTest.php看起来像这样:
<?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 shows up only when the test script is ran through './vendor/bin/phpunit' The test class seems to be initiated without the dependency stated and throws an error. 仅当测试脚本通过'./vendor/bin/phpunit'运行时才会显示错误。测试类似乎在没有声明依赖项的情况下启动并引发错误。 Does anyone know how to fix this? 有谁知道如何解决这一问题? Thanks in advance. 提前致谢。
You cannot inject classes into the tests (as far as i know), given that they are not resolved automatically by laravel/phpUnit. 你不能将类注入到测试中(据我所知),因为它们不是由laravel / phpUnit自动解决的。
The correct way is to make
(resolve) them through laravel's app
facade. 正确的方法是通过laravel的app
外观make
(解决)它们。 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 资料来源: http : //laravel.com/docs/5.1/container
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.