Codeigniter can not mock any object using aspectmock

681 views Asked by At

I make a new and clean Codeigniter 2.2.1 project to test this issue.

my environment:

MacOSX 10.10

PHP 5.6.8 (cli) (built: Apr 20 2015 10:59:03)
Copyright (c) 1997-2015 The PHP Group
Zend Engine v2.6.0, Copyright (c) 1998-2015 Zend Technologies
    with Xdebug v2.2.3, Copyright (c) 2002-2013, by Derick Rethans

Codigniter 2.2.1

Codeception: *

Codeception/aspectmock: *

and I do so many hack to integrate with codeception

finally, I can testing with &get_instance() function and everything can run normally.

But,

when I want to mock a model or Lib class

there does not happen what I expect for.

here is my _bootstrap file

include __DIR__.'/../vendor/autoload.php'; // composer autoload

$kernel = \AspectMock\Kernel::getInstance();
$kernel->init([
    'debug' => true,
    'includePaths' => [
        __DIR__.'/../application',
        __DIR__.'/../system',
    ],
    "excludePaths" => [
        __DIR__
    ],
    "cacheDir" => "/tmp/mock_cache",
    "appDir" => __DIR__.'/..',
    "vendor" => __DIR__.'/../vendor'
]);

.....
Codeigniter hack and my autoload
.....

and then I create a unit test

php vendor/bin/codecep g:test unit pub

oh, yes, I must create "pub" class to application/models folders

and then add it to autoload config

and the pub class have a public function called gogo()

it will return "123" string

class pub extends CI_Model
{
    public function gogo()
    {
        return "123";
    }
}

I want to mock this to return "456"

so my test file is

use AspectMock\Test as test;

...
protected $CI;

protected function _before()
{
    $this->CI = &get_instance();
}

protected function _after()
{
    \AspectMock\Test::clean();
}

// tests
public function testMe()
{
    $mymodel = test::double("pub", ["gogo" => "456"]);

    $this->assertEquals("456", $this->CI->pub->gogo());
}

the result is fail

Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'456'
+'123'

what step is wrong?

1

There are 1 answers

1
kenjis On

CodeIgniter does not have real autoloader. Try this: https://github.com/Codeception/AspectMock#without-autoloader