Laravel Testing Service Dependency Injection Error(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 测试服务依赖注入错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Laravel 测试服务依赖注入错误
- PHP Count 布尔数组中真值的数量 2021-01-01
- 带有通配符的 Laravel 验证器 2021-01-01
- 如何定位 php.ini 文件 (xampp) 2022-01-01
- SoapClient 设置自定义 HTTP Header 2021-01-01
- 没有作曲家的 PSR4 自动加载 2022-01-01
- Laravel 仓库 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- Mod使用GET变量将子域重写为PHP 2021-01-01
- 正确分离 PHP 中的逻辑/样式 2021-01-01
- 从 PHP 中的输入表单获取日期 2022-01-01