PHP code example of kartavik / php-mock

1. Go to this page and download the library: Download kartavik/php-mock 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/ */

    

kartavik / php-mock example snippets


namespace foo;

$time = time(); // This call can be mocked, a call to \time() can't.

namespace foo;

use phpmock\MockBuilder;

$builder = new MockBuilder();
$builder->setNamespace(__NAMESPACE__)
    ->setName("time")
    ->setFunction(
        function () {
            return 1417011228;
        }
    );
                    
$mock = $builder->build();

// The mock is not enabled yet.
assert (time() != 1417011228);

$mock->enable();
assert (time() == 1417011228);

// The mock is disabled and PHP's built-in time() is called.
$mock->disable();
assert (time() != 1417011228);

namespace foo;

use Kartavik\PHPMock\MockBuilder;
use Kartavik\PHPMock\Functions\FixedValue;

$builder = new MockBuilder();
$builder->setNamespace(__NAMESPACE__)
    ->setName("time")
    ->setFunctionProvider(new FixedValueFunction(1417011228));

$mock = $builder->build();

namespace foo;

use Kartavik\Environment\SleepBuilder;

$builder = new SleepEnvironmentBuilder();
$builder->addNamespace(__NAMESPACE__)
    ->setTimestamp(1417011228);

$environment = $builder->build();
$environment->enable();

// This won't delay the test for 10 seconds, but increase time().        
sleep(10);

assert(1417011228 + 10 == time());