Patching functions with when()

The first way Brain Monkey offers to monkey patch a function is Functions\when().

This function has to be used to set a behavior for functions.

when() and 5 related methods are used to define functions (if not defined yet) and:

  • make them return a specific value

  • make them return one of the received arguments

  • make them echo a specific value

  • make them echo one of the received arguments

  • make them behave just like another callback

For the sake of readability, in all the code samples below I'll assume that an use statement is in place:

use Brain\Monkey\Functions;

Don't forget to add it in your code as well, or use the fully qualified class name.

Also be sure to read the PHP Functions / Setup section that explain how setup Brain Monkey for usage in tests.

justReturn()

By using when() in combination with justReturn() you can make a (maybe) undefined function just return a given value:

Functions\when('a_undefined_function')->justReturn('Cool!');

echo a_undefined_function(); // echoes "Cool!"

Without passing a value to justReturn() the target function will return nothing (null).

returnArg()

This other when-related method is used to make the target function return one of the received arguments, by default the first.

Note that if the target function does not receive the desired argument, returnArg() throws an exception:

justEcho()

Similar to justReturn(), it makes the mocked function echo some value instead of returning it.

echoArg()

Similar to returnArg(), it makes the mocked function echo some received argument instead of returning it.

alias()

The last of the when-related methods allows to make a function behave just like another callback. The replacing function can be anything that can be run: a core function or a custom one, a class method, a closure...

Last updated