Php Codeigniter:如何测试在构造函数中获取控制器实例的库?
我有以下名为Item_service的库:Php Codeigniter:如何测试在构造函数中获取控制器实例的库?,php,codeigniter,unit-testing,testing,phpunit,Php,Codeigniter,Unit Testing,Testing,Phpunit,我有以下名为Item_service的库: class Item_Service { private $items; function __construct(Items $items) { $this->items = $items; } 其中Items是controllers/Items.php的一个实例。 在名为Items\u test.php的测试类中我尝试使用以下行加载Item\u服务库: $items = $this->CI->load->libr
class Item_Service {
private $items;
function __construct(Items $items)
{
$this->items = $items;
}
其中Items
是controllers/Items.php
的一个实例。
在名为Items\u test.php的测试类中
我尝试使用以下行加载Item\u服务
库:
$items = $this->CI->load->library('items/Item_service');
但后来我得到了错误的说法
TypeError: Argument 1 passed to Item_Service::__construct() must be an instance of Items, null given
我的测试类是基于kenjis/ci phpunit test
编写的
我应该如何将控制器注入该库中以测试该库?另外,我可以测试控制器本身吗?控制器中有许多帮助器方法。答案是将其作为第二个参数在数组中传递给库调用。例如:
library('items/Item_service',array('controller'=>this->CI))代码>
然后,从您的服务的构造中,不要引用项目-它将是一个数组,但您的项目将在“控制器”键上可用
$this->items=$items['controller']代码>@NikuNj Rathod-为什么在编辑中向OP的问题添加了额外的代码?是的@MagnusEriksson。我刚刚拒绝了这个编辑,因为它显然与OP的意图相冲突。在我的例子中,$这不是controller的实例-它是Test类的实例,那么它不是$this->CI吗?$this->CI,然后呢?如何判断要加载哪个控制器?但是为什么不从控制器本身调用此测试,然后$this->CI将引用该测试?如果您想测试控制器-当然要从控制器本身运行测试?您可能想看看我认为这可能是对您的查询的直接答案,但我认为您可以解决您的挑战,但只需从控制器本身调用即可。