AspectMock not working in Codeception framework & yii2 framework

37 views Asked by At

I want to mock the static methods, so I am using the AspectMock library https://github.com/Codeception/AspectMock.

I tried to mock one static method but it doesnt return the expected mocked result.

Configuration: tests/_bootstrap.php

<?php

define('YII_ENV', 'test');
defined('YII_DEBUG') or define('YII_DEBUG', true);

require_once __DIR__ . '/../vendor/yiisoft/yii2/Yii.php';
require __DIR__ . '/../vendor/autoload.php';

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

Actual Test:

<?php

namespace models;

use app\models\Settings;
use AspectMock\Test as test;

class SampleMockExampleTest extends \Codeception\Test\Unit {

    /**
     * @var \UnitTester
     */
    protected $tester;

    protected function _before() {
        
    }

    protected function _after() {
//        test::clean(); // remove all registered test doubles
    }

    /**
     * 
     */
    public function testMockExample() {
        test::double('app\models\Settings', ['getSettings' => "mock"]);
        var_dump(Settings::getSettings());
        exit;
    }
}
1

There are 1 answers

0
Omi On

While configuring you need to configure according to the php framework you are using. I am using the yii2 framework and found some different settings for the Yii2 framework. Please check the configuration for the framework here https://github.com/Codeception/AspectMock/wiki/Example-configs#yii2.

Instead of require_once __DIR__ . '/../vendor/yiisoft/yii2/Yii.php';, we need to use $kernel->loadFile(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php');

Here is my working configuration for the Yii2 framework:

tests/_bootstrap.php

<?php

define('YII_ENV', 'test');
defined('YII_DEBUG') or define('YII_DEBUG', true);

require __DIR__ . '/../vendor/autoload.php';

$kernel = AspectMock\Kernel::getInstance();
$kernel->init([
    'debug' => true,
    'includePaths' => [__DIR__ . '/../models'],
    'appDir' => __DIR__ . '/..',
    'excludePaths' => [__DIR__, '/../vendor/codeception', '/../vendor/phpunit'],
    'cacheDir' => '/tmp',
]);
$kernel->loadFile(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php');