从结论开始,我得到了这个错误:
[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();
}
}
只有在测试脚本通过&#39; ./ vendor / bin / phpunit&#39;似乎在没有声明依赖项的情况下启动测试类并抛出错误。有谁知道如何解决这一问题?提前谢谢。
答案 0 :(得分:5)
你不能将类注入测试中(据我所知),因为laravel / phpUnit不会自动解析它们。
正确的方法是通过laravel的make
门面app
(解决)它们。您的测试脚本应如下所示:
<?php
class SomeValidatorTest extends TestCase
{
public function __construct()
{
$this->validator = \App::make('App\Services\Validators\SomeValidator');
}
public function testBasicExample()
{
$result = $this->validator->doSomething();
}
}