【问题标题】:Codeigniter: how to test library that takes Controller instance in constructor?Codeigniter:如何测试在构造函数中使用 Controller 实例的库?
【发布时间】:2017-12-08 08:29:13
【问题描述】:

我有以下名为 Item_service 的库:

class Item_Service {
private $items;

function __construct(Items $items)
{
    $this->items = $items;
}

其中Itemscontrollers/Items.php 的一个实例。 在名为Items_test.php 的测试类中,我尝试使用以下行加载Item_service 库:

$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编写的。

我应该如何将控制器注入这个库以便能够测试这个库?另外,我可以测试控制器本身吗?控制器内部有很多辅助方法。

【问题讨论】:

  • @NikuNj Rathod - 为什么您在编辑中为 OP 的问题添加了额外的代码?
  • 是的@MagnusEriksson。我刚刚拒绝了该编辑,因为它显然与 OP 的意图相冲突

标签: php codeigniter unit-testing testing phpunit


【解决方案1】:

答案是将它作为第二个参数在数组中传递给库调用。比如:

library('items/Item_service',array('controller'=>$this->CI));

然后从您的服务构造中不要引用 Items - 这将是一个数组,但是您的 Items 将在“控制器”键上可用。

$this->items = $items['controller'];

【讨论】:

  • 在我的例子中 $this 不是控制器的实例 - 它是测试类的实例
  • 那不就是$this->CI吗?
  • $this->CI 然后呢?如何判断要加载哪个控制器?
  • 但是你为什么不从控制器本身调用这个测试然后 $this->CI 会引用它呢?如果您想测试控制器 - 一定要从控制器本身运行测试吗?
  • 您可能想查看stackoverflow.com/questions/14165895,我认为这可能是您查询的直接答案,但我认为您可以解决您的挑战,但只需从控制器本身调用。
猜你喜欢
  • 2023-04-07
  • 1970-01-01
  • 1970-01-01
  • 2017-07-20
  • 1970-01-01
  • 2022-01-24
  • 1970-01-01
  • 2019-11-27
  • 2018-11-24
相关资源
最近更新 更多