kenjis / ci-app-for-ci-phpunit-test

CodeIgniter Test Application for ci-phpunit-test
31 stars 20 forks source link

Example for Mock_Libraries_Email #19

Open luckydonald opened 6 years ago

luckydonald commented 6 years ago

I have trouble adding it.

luckydonald commented 6 years ago

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('no-reply@example.com')
      ->to('me@example.com')
      ->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 commented 6 years ago

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 commented 6 years ago

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 commented 6 years ago

So with

class Mock_Libraries_Email extends CI_Email {

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

luckydonald commented 6 years ago

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.");
        }