PHP code example of jeremeamia / func-mocker

1. Go to this page and download the library: Download jeremeamia/func-mocker 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/ */

    

jeremeamia / func-mocker example snippets


use My\App\RandomNumberGenerator;
use FuncMocker\Mocker;

Mocker::mock('rand', 'My\App', function () {
    return 5;
});

$rng = new RandomNumberGenerator(1, 10);
echo $rng->getNumber();
//> 5
echo $rng->getNumber();
//> 5
echo $rng->getNumber();
//> 5



namespace My\App\Tests;

use FuncMocker\Mocker as FuncMocker;
use My\Crypto\Signer;
use Psr\Http\Message\RequestInterface as Request;

class SignerTest extends \PHPUnit_Framework_TestCase
{
    // ...

    public function testCanGetStringToSign()
    {
        // Mock the request with PHPUnit
        $request = $this->getMock(Request::class);
        $request->method('getMethod')->willReturn('POST');
        $request->method('getHeader')->willReturn(['CREATE_THING']);
        $request->method('getBody')->willReturn('PARAMS');
        
        // Mock the call to PHP's time() function to give us a deterministic value.
        FuncMocker::mock('time', 'My\Crypto', function () {
            return 12345;
        });
                
        $signer = new Signer();
        
        // Check to see that the string to sign is constructed how we would expect.
        $this->assertEquals(
            "POST\n12345\nCREATE_THING\nPARAMS",
            $signer->getStringToSign()
        );
    }
    
    // ...
}


$func = FuncMocker\Mocker::mock('time()', 'My\App', function () {
    return 1234567890;
});

echo My\App\time();
//> 1234567890

$func->disable();
echo My\App\time();
//> 1458018866

$func->enable();
echo My\App\time();
// > 1234567890
 php


namespace My\Crypto;

use Psr\Http\Message\RequestInterface as Request;

class Signer
{
    // ...

    public function getStringToSign(Request $request)
    {
        return $request->getMethod() . "\n"
            . time() . "\n"
            . $request->getHeader('X-API-Operation')[0] . "\n"
            . $request->getBody();            
    }
    
    // ...
}