3

I have the following Library called Item_service:

class Item_Service {
private $items;

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

Where Items is an instance of controllers/Items.php. In my test class called Items_test.php i try to load the Item_service library using the following line:

$items = $this->CI->load->library('items/Item_service');

But then I get error saying

TypeError: Argument 1 passed to Item_Service::__construct() must be an instance of Items, null given

My test class is written based on kenjis/ci-phpunit-test.

How should I inject the controller into this library to be able to test the library? Also, can I test the controller itself? There are a lot of helper methods inside the controller.

1 Answers1

0

The answer is to pass it within an array as the second param to the library call. So for example:

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

Then from the construct of your service don't reference Items - it will be an array but then your Items will be available on the 'controller' key.

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

Antony
  • 3,875
  • 30
  • 32
  • In my case $this is NOT an instance of controller - it is an instance of Test Class – Michał Śnieżko Dec 08 '17 at 08:45
  • So would it not then be $this->CI? – Antony Dec 08 '17 at 08:46
  • $this->CI and then what? How to tell which controller to load? – Michał Śnieżko Dec 08 '17 at 08:48
  • But why don't you call this test from the controller itself and then $this->CI will reference that? If you want to test the controller - surely run the test from the controller itself? – Antony Dec 08 '17 at 08:54
  • You might want to look at https://stackoverflow.com/questions/14165895 which I believe is possibly the direct answer to your query but I reckon that you can solve your challenge but just by calling from the controller itself. – Antony Dec 08 '17 at 08:56
  • I am not trying to test a controller. I have a LIBRARY MyLibrary.php and this library has the folllowing constructor: `__construct(Controller controllerObject){$this->controllerObject = controllerObject)}`. I am trying to test this LIBRARY in my TEST class. But to be able to test it, I have to pass Controller object in constructor in my TEST class. – Michał Śnieżko Dec 08 '17 at 09:33
  • Then as per the answer 14165895 I'm not sure you can call controllers outside the main CI scope I'm afraid. – Antony Dec 08 '17 at 09:51