A PHP testing library that mocks non-deterministic built-in functions like time() and rand() using namespace fallback.
PHP-Mock is a testing library that mocks non-deterministic built-in PHP functions like time(), rand(), and exec() within namespaced code. It leverages PHP's namespace fallback policy to intercept unqualified function calls, allowing developers to create predictable and repeatable test environments. This solves the problem of testing code that depends on functions with variable outputs, such as time-sensitive operations or random number generation.
PHP developers writing unit tests for applications that rely on built-in PHP functions with non-deterministic behavior, particularly those using testing frameworks like PHPUnit, Mockery, or Prophecy. It is also suitable for developers who need to mock functions like sleep() or microtime() without halting test execution.
Developers choose PHP-Mock because it provides a lightweight, extension-free approach to mocking built-in functions by utilizing native PHP namespace behavior, avoiding dependencies on external extensions like APD, runkit, or UOPZ. Its seamless integrations with popular testing frameworks and built-in function providers (e.g., FixedValueFunction, SleepFunction) simplify test setup and management.
Mock built-in PHP functions (e.g. time(), exec() or rand())
Open-Awesome is built by the community, for the community. Submit a project, suggest an awesome list, or help improve the catalog on GitHub.
Uses PHP's native namespace fallback policy instead of external extensions like APD or runkit, making it lightweight and easy to install without system-level changes.
Provides dedicated packages for PHPUnit, Mockery, and Prophecy, reducing setup time by integrating directly with popular testing frameworks.
Includes ready-to-use providers like FixedValueFunction and SleepFunction for common cases such as time() and sleep(), minimizing custom mock implementation.
Allows grouping multiple mocked functions into environments, e.g., SleepEnvironmentBuilder synchronizes time() and sleep() mocks for realistic time-based testing.
Offers Spy class to track function invocations with arguments and return values, enabling detailed assertions without altering the original function behavior.
Cannot mock fully-qualified function calls (e.g., \time()), forcing code to use unqualified calls within namespaces, which may require significant refactoring in some projects.
Mocks must be defined before the first unqualified call in a namespace due to PHP bug #68541, potentially complicating test setup or requiring workarounds like isolated processes.
Focuses only on PHP's built-in functions; cannot mock user-defined functions or functions from extensions, restricting its use in broader testing scenarios.
Enabled mocks alter global state and must be carefully disabled after tests to avoid affecting subsequent tests, adding overhead to test cleanup and maintenance.