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 测试服务依赖注入错误
基础教程推荐
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- 在多维数组中查找最大值 2021-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01