ci-app-for-ci-phpunit-test icon indicating copy to clipboard operation
ci-app-for-ci-phpunit-test copied to clipboard

Example for Mock_Libraries_Email

Open luckydonald opened this issue 7 years ago • 5 comments

I have trouble adding it.

luckydonald avatar Jun 01 '18 13:06 luckydonald

I try to mock the mail loaded in a controller.

class Whatever_controller extends CI_Controller {
  function index() {
    $this->load->library('email');

    $this->email->clear()
      ->from('[email protected]')
      ->to('[email protected]')
      ->subject('Test')
      ->send();
  }
}
class Test extends TestCase {
  protected function setUp() {
    $this->resetInstance();
    $this->CI->load->database();
    // Mock email
    $this->CI->email = new Mock_Libraries_Email();
    $this->mock_mail = &$this->CI->email;
  }
  function test_foo() {
    $output = $this->request('POST', 'whatever/index);
  }
}

luckydonald avatar Jun 01 '18 13:06 luckydonald

However the controller is loading the stock email, which will send normally, and $this->mock_mail is still unchanged (->_get_data() is empty array).

luckydonald avatar Jun 01 '18 13:06 luckydonald

With

protected function setUp() {
		$this->resetInstance();
		$this->CI->load->database();
		$email = new Mock_Libraries_Email();
		$this->request->setCallable(
			function ($CI) use ($email){
				$CI->email = $email;
			}
		);
		$this->mock_mail = $email;
		parent::setUp();
	}

I can install it to the actual running request controller instance but will get the error because of an isinstance check: Resource 'email' already exists and is not a CI_Email instance.

luckydonald avatar Jun 01 '18 14:06 luckydonald

So with

class Mock_Libraries_Email extends CI_Email {

I can work around that, but now have inherited many stuff from the original.

luckydonald avatar Jun 01 '18 14:06 luckydonald

Some brainstorming:

class Mock_Libraries_Email extends CI_Email {
	const MOCK_OF = CI_Email::class;

/tests/_ci_phpunit_test/replacing/core/Loader.php

// function _ci_init_library

		if (isset($CI->$object_name))
		{
+			if ($CI->$object_name::MOCK_OF == $class_name)
+			{
+				log_message('debug', $object_name." has already been instantiated as mock of ".$class_name.'". Second attempt aborted.");
+				return;
+			}
			if ($CI->$object_name instanceof $class_name)
			{
				log_message('debug', $class_name." has already been instantiated as '".$object_name."'. Second attempt aborted.");
				return;
			}

			show_error("Resource '".$object_name."' already exists and is not a ".$class_name." instance.");
		}

luckydonald avatar Jun 01 '18 14:06 luckydonald