PHP code example of cheprasov / php-extra-mocks

1. Go to this page and download the library: Download cheprasov/php-extra-mocks library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

cheprasov / php-extra-mocks example snippets


namespace A;

class A
{
    public static function string_length($str)
    {
        return strlen($str);
    }
}

namespace B;

class B {

    public static function string_length($str)
    {
        return strlen($str);
    }
}

namespace Example;

ks;

// 1. Redefine Global Function by Function

\ExtraMocks\Mocks::mockGlobalFunction(
    '\A\strlen',
    function($s) {
        return strlen($s) * 5;
    }
);

echo \A\A::string_length('foo') . PHP_EOL; // 15
echo \B\B::string_length('foo') . PHP_EOL; // 3;

// 2. Redefine Global Function by Result

\ExtraMocks\Mocks::mockGlobalFunction('\A\strlen', 42);

echo \A\A::string_length('foo') . PHP_EOL; // 42;
echo \B\B::string_length('foo') . PHP_EOL; // 3;

// 3. Redefine Global Function by Result once

\ExtraMocks\Mocks::mockGlobalFunction('\A\strlen', 42, 1);

echo \A\A::string_length('foo') . PHP_EOL; // 42;
echo \A\A::string_length('foo') . PHP_EOL; // 3;
echo \B\B::string_length('foo') . PHP_EOL; // 3;

// 3. Get count of calls mocked function

\ExtraMocks\Mocks::mockGlobalFunction('\A\strlen', 42);

echo Mocks::getCountCalls('\A\strlen') . PHP_EOL; // 0
echo \A\A::string_length('foo') . PHP_EOL;        // 42;
echo Mocks::getCountCalls('\A\strlen') . PHP_EOL; // 1
echo \A\A::string_length('foo') . PHP_EOL;        // 42;
echo Mocks::getCountCalls('\A\strlen') . PHP_EOL; // 2