Codeception / AspectMock

The most powerful and flexible mocking framework for PHPUnit / Codeception.
MIT License
790 stars 129 forks source link

AspectMock not working in Codeception framework & yii2 framework #207

Closed omprakash-pachkawade-jiem closed 1 year ago

omprakash-pachkawade-jiem commented 1 year ago

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;
    }
}

Issue: Here is my sample unit test case. I have mocked the getSettings method which will return the output as mock. But when I tried to call the static method Settings::getSettings() it didn't return the mocked result instead it returned the actual output.

SamMousa commented 1 year ago

No information about what is wrong or what the output is...

omprakash-pachkawade-jiem commented 1 year ago

@SamMousa,

I have updated the question, The mocked method doesn't return the mocked result, it returns the actual result.

omprakash-pachkawade-jiem commented 1 year ago

Here is the answer to this issue: 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.

Here is the my working configuration for Yii2 framework:

<?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');