Download the PHP package jeremeamia/func-mocker without Composer
On this page you can find all versions of the php package jeremeamia/func-mocker. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download jeremeamia/func-mocker
More information about jeremeamia/func-mocker
Files in jeremeamia/func-mocker
Package func-mocker
Short Description Allows you to override global function used within a namespace for the purposes of testing.
License MIT
Homepage https://github.com/jeremeamia/php-func-mocker
Informations about the package func-mocker
PHP FuncMocker
FuncMocker – Mocking PHP functions like a... punk rocker?
Allows you to overwrite (i.e., mock) global functions used within a given namespace for the purposes of testing.
There are two main use cases I developed this for:
- When you are testing objects that call non-deterministic functions like
time()
andrand()
, and you need these functions to return deterministic values for the sake of the test. - When you are working with code where you have objects that must make calls to functions. This is pretty common in
legacy codebases that were not previously object-oriented in nature. For example, if you're project has a function
called
db_add()
that you end up using in an object in your model layer, you might want to "mock" that function when you are testing so you don't actually make calls to the database in your unit tests.
The simple technique behind this code is described in this blog post by Fabian Schmengler. Basically, it involves taking advantage of PHP's namespace resolution rules.
Install
Via Composer
Usage
Let's you have a RandomNumberGenerator
class in the namespace, My\App
, that calls the global function rand()
.
You could overwrite the usage of rand()
for that particular namespace by using FuncMocker.
Longer Example
Assume there is a class that uses the global function (e.g., time()
) that you'd like to mock.
Here is an example of a PHPUnit test that uses FuncMocker to mock time()
to return a fixed value, making it much
easier to write a test.
Disabling and Re-Enabling
FuncMocker also lets you disable mocks you've setup, in case you need the function to behave normally in your some of your tests.
Limitations
- The function to be mocked must be used in a namespace other than the global namespace.
- The function to be mocked must not be referenced using a fully-qualified name (e.g.,
\time()
).
Testing
Credits
- Jeremy Lindblom - Main author.
- Marius Sarca - Borrowed his stream wrapper include technique from opis/closure.
Alternatives
- Do it yourself. See the following articles:
- php-mock/php-mock - Similar function mocking library I found afterwards.
- Patchwork - More robust mocking library that can intercept calls to functions.
- Atoum - Fullf-featured test framework with function mocking included.
License
The MIT License (MIT). Please see License File for more information.