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 测试服务依赖注入错误


基础教程推荐
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 如何替换eregi() 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01