Laravel 测试服务依赖注入错误 [英] Laravel Testing Service Dependency Injection Error

查看:19
本文介绍了Laravel 测试服务依赖注入错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从结论开始,我得到这个错误:

To start from the conclusion, I get this error:

[ErrorException]                                                                                                                                                                                    
Argument 1 passed to SomeValidatorTest::__construct() must be an instance of AppServicesValidatorsSomeValidator, 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 AppServicesValidators;

use AppServicesSomeDependency;

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 AppServicesValidatorsSomeValidator;


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('AppServicesValidatorsSomeValidator');
    }

    public function testBasicExample()
    {
        $result = $this->validator->doSomething();
    }
}

来源:http://laravel.com/docs/5.1/container

这篇关于Laravel 测试服务依赖注入错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆