Laravel测试服务依赖注入错误 [英] 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
在Laravel应用中,我有一个名为"SomeValidator.php"的脚本,如下所示:
In Laravel app, I have a script called "SomeValidator.php" which 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);
}
}
运行没有错误.
然后,测试脚本SomeValidatorTest.php如下所示:
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();
}
}
仅当测试脚本通过'./vendor/bin/phpunit'运行时,才会显示错误.测试类似乎是在没有声明依赖项的情况下启动的,并引发错误.有谁知道如何解决这一问题?预先感谢.
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. Does anyone know how to fix this? Thanks in advance.
推荐答案
鉴于laravel/phpUnit无法自动解析类,因此您无法将类注入测试(据我所知).
You cannot inject classes into the tests (as far as i know), given that they are not resolved automatically by laravel/phpUnit.
正确的方法是通过laravel的app
外观make
(解析)它们.您的测试脚本应如下所示:
The correct way is to make
(resolve) them through laravel's 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();
}
}
来源: http://laravel.com/docs/5.1/container
这篇关于Laravel测试服务依赖注入错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!