从结论开始,我得到了这个错误:
[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”的脚本,如下所示:
<?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 看起来像这样:
<?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”运行时才会出现错误测试类似乎在没有声明依赖项的情况下启动并抛出错误。有谁知道如何解决这一问题?提前致谢。
最佳答案
你不能将类注入(inject)到测试中(据我所知),因为它们不会被 laravel/phpUnit 自动解析。
正确的方法是通过 laravel 的 app
facade make
(解析)它们。您的测试脚本应如下所示:
<?php
class SomeValidatorTest extends TestCase
{
public function __construct()
{
$this->validator = \App::make('App\Services\Validators\SomeValidator');
}
public function testBasicExample()
{
$result = $this->validator->doSomething();
}
}
关于php - Laravel 测试服务依赖注入(inject)错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33363499/