Php mocking a function outside of a class

Viewed 484

The Mockery docs have examples for mocking classes and their members but I don't see any details for mocking included functions. I would like to mock the implementation for wp_send_json() which is brought in by /wp-includes/functions.php. Mockery or any other php library may be used.

Here is a usage of wp_send_json(). Overriding this function will allow me to run json_encode() on an input value and then return it for a clean unit test:

function handleAjax() {
   $name = $_POST['name'];
   return wp_send_json($name);
}

In my test suite I call it like this:

use \Symfony\Component\HttpFoundation\Request;

class UtilitiesTest extends \Codeception\TestCase\WpTestCase {
  _before() {

  }

  testHandleAjax() {
    $request = Request::create(
      null,
      'POST',
      ['name' => 'John']
    );
    $request->overrideGlobals(); // $_POST is now mocked

    $result = handleAjax();
    $this->assertEquals('John', $result);
  }
}

How can the classless function wp_send_json() be mocked/overridden for testing?

1 Answers

With php-mock it's possible to mock global functions.

Example

composer require --dev php-mock/php-mock
namespace Test;

use phpmock\MockBuilder;

$builder = new MockBuilder();
$builder->setNamespace(__NAMESPACE__)
        ->setName('wp_send_json')
        ->setFunction(
            function ($response) {
                // echo json_encode($response);
            }
        );

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

wp_send_json(['success' => true]);
Related