繁体   English   中英

Laravel测试服务依赖注入错误

[英]Laravel Testing Service Dependency Injection 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”的脚本,如下所示:

<?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'运行时才会显示错误。测试类似乎在没有声明依赖项的情况下启动并引发错误。 有谁知道如何解决这一问题? 提前致谢。

你不能将类注入到测试中(据我所知),因为它们不是由laravel / phpUnit自动解决的。

正确的方法是通过laravel的app外观make (解决)它们。 您的测试脚本应如下所示:

<?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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM