PHP code example of chmeldax / phpmocks

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

    

chmeldax / phpmocks example snippets


$doubleBuilder = new \Chmeldax\PhpMocks\Double\Builder($className);
$doubleBuilder
    ->allowMethodCall('methodToBeStubbed')
    ->with(new Constraints\Anything, new Constraints\Anything, null) // Specify allowed parameters
    ->andReturn('return_value_1');
$double = $doubleBuilder->build(); // This is the stub

$doubleBuilder
    ->allowMethodCall('methodToBeStubbed')
    ->with(new Constraints\Anything, new Constraints\Anything, null) // Specify allowed parameters
    ->andReturn('return_value_1', 'return_value_2'); // Returns different values on #1 and #2 call

$doubleBuilder
    ->allowMethodCall('methodToBeStubbed')
    ->with(new Constraints\Anything, new Constraints\Anything, null) // Specify allowed parameters
    ->andInvoke(function ($a, $b, $c) { // specify your own callback
        return 'return_value'
      });

$doubleBuilder = new \Chmeldax\PhpMocks\Double\Builder($instance);
$doubleBuilder
    ->allowMethodCall('methodToBeStubbed')
    ->with(new Constraints\Anything, new Constraints\Anything, null) // Specify allowed parameters
    ->andCallOriginal(); // Calls the original method from $instance

$doubleBuilder
    ->allowMethodCall('methodToBeStubbed')
    ->with(new Constraints\Anything, new Constraints\Anything, 'first')
    ->andReturn('return_value_1'); // Returns different values on #1 and #2 call

$doubleBuilder
    ->allowMethodCall('methodToBeStubbed')
    ->with(new Constraints\Anything, new Constraints\Anything, 'second') // Different parameter value
    ->andReturn('return_value_2');

$double = $doubleBuilder->build();
$double->methodToBeStubbed(1, 2, 'first');  // returns 'return_value_1'
$double->methodToBeStubbed(1, 2, 'second'); // returns 'return_value_2'

$doubleBuilder
    ->expectMethodCall('methodToBeMocked')
    ->with(new Constraints\Anything, new Constraints\Anything, null)
    ->times(10) // Expectation
    ->andReturn('return_value_1');

$doubleBuilder
    ->expectMethodCall('methodToBeMocked')
    ->with(new Constraints\Anything, new Constraints\Anything, 'first')
    ->atCalls(1, 3) // Expectation for 1st and 3rd call (counted globally for all "with" blocks)
    ->andReturn('return_value_1');

$doubleBuilder
    ->expectMethodCall('methodToBeMocked')
    ->with(new Constraints\Anything, new Constraints\Anything, 'second')
    ->atCall(2) // Expectation for 2nd call (counted globally for all "with" blocks)
    ->andReturn('return_value_2');

$doubleBuilder->checkExpectations() // Throws exception if any expectation is not met