PHPackages                             kartavik/php-mock - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Testing &amp; Quality](/categories/testing)
4. /
5. kartavik/php-mock

ActiveLibrary[Testing &amp; Quality](/categories/testing)

kartavik/php-mock
=================

PHP-Mock can mock built-in PHP functions (e.g. time()). PHP-Mock relies on PHP's namespace fallback policy. No further extension is needed.

3.0.1(7y ago)0271MITPHPPHP ^7.2

Since Nov 26Pushed 7y ago1 watchersCompare

[ Source](https://github.com/KartaviK/php-mock)[ Packagist](https://packagist.org/packages/kartavik/php-mock)[ RSS](/packages/kartavik-php-mock/feed)WikiDiscussions master Synced 2d ago

READMEChangelog (2)Dependencies (4)Versions (16)Used By (1)

PHP-Mock: mocking built-in PHP functions
========================================

[](#php-mock-mocking-built-in-php-functions)

[![Build Status](https://camo.githubusercontent.com/3975719f820eb6301f274e36b8af15eb452449879e2242f0ef83e48224af2ed3/68747470733a2f2f7472617669732d63692e636f6d2f4b6172746176694b2f7068702d6d6f636b2e7376673f6272616e63683d6d6173746572)](https://travis-ci.com/KartaviK/php-mock)[![codecov](https://camo.githubusercontent.com/2fe4f18285a5fa961f21d98f9886fb69217a7d51f8367fbb8b26f9e3172ad849/68747470733a2f2f636f6465636f762e696f2f67682f4b6172746176694b2f7068702d6d6f636b2f6272616e63682f6d61737465722f67726170682f62616467652e737667)](https://codecov.io/gh/KartaviK/php-mock)

PHP-Mock is a testing library which mocks non deterministic built-in PHP functions like `time()` or `rand()`. This is achieved by [PHP's namespace fallback policy](http://php.net/manual/en/language.namespaces.fallback.php):

> PHP will fall back to global functions \[…\] if a namespaced function \[…\] does not exist.

PHP-Mock uses that feature by providing the namespaced function. I.e. you have to be in a **non global namespace** context and call the function **unqualified**:

```
namespace foo;

$time = time(); // This call can be mocked, a call to \time() can't.
```

Requirements and restrictions
-----------------------------

[](#requirements-and-restrictions)

- Only *unqualified* function calls in a namespace context can be mocked. E.g. a call for `time()` in the namespace `foo` is mockable, a call for `\time()` is not.
- The mock has to be defined before the first call to the unqualified function in the tested class. This is documented in [Bug #68541](https://bugs.php.net/bug.php?id=68541). In most cases, you can ignore this restriction but if you happen to run into this issue you can call `Mock::define()`before that first call. This would define a side effectless namespaced function which can be enabled later. Another effective approach is running your test in an isolated process.

Alternatives
------------

[](#alternatives)

If you can't rely on or just don't want to use the namespace fallback policy, there are alternative techniques to mock built-in PHP functions:

- [**PHPBuiltinMock**](https://github.com/jadell/PHPBuiltinMock) relies on the [APD](http://php.net/manual/en/book.apd.php) extension.
- [**MockFunction**](https://github.com/tcz/phpunit-mockfunction) is a PHPUnit extension. It uses the [runkit](http://php.net/manual/en/book.runkit.php) extension.
- [**UOPZ**](https://github.com/krakjoe/uopz) is a Zend extension which allows, among others, renaming and deletion of functions.
- [**vfsStream**](https://github.com/mikey179/vfsStream) is a stream wrapper for a virtual file system. This will help you write tests which covers PHP stream functions (e.g. `fread()` or `readdir()`).

Installation
============

[](#installation)

Use [Composer](https://getcomposer.org/):

```
composer require --dev kartavik/php-mock
```

Usage
=====

[](#usage)

You don't need to learn yet another API. PHP-Mock has integrations for these testing frameworks:

- [kartavik/php-mock-phpunit](https://github.com/php-mock/php-mock-phpunit) - PHPUnit integration

**Note:** If you plan to use one of the above mentioned testing frameworks you can skip reading any further and just go to the particular integration project.

PHP-Mock API
------------

[](#php-mock-api)

Create a `Mock`object. You can do this with the fluent API of `MockBuilder`:

- `MockBuilder::setNamespace()`sets the target namespace of the mocked function.
- `MockBuilder::setName()`sets the name of the mocked function (e.g. `time()`).
- `MockBuilder::setFunction()`sets the concrete mock implementation.
- `MockBuilder::setFunctionProvider()`sets, alternativly to `MockBuilder::setFunction()`, the mock implementation as a `FunctionProvider`:

    - `FixedValueFunction`is a simple implementation which returns always the same value.

    \*`FixedMicrotime`is a simple implementation which returns always the same microtime. This class is different to `FixedValueFunction` as it contains a converter for `microtime()`'s float and string format.

    - `FixedDate`is a simple implementation which returns always a formated date for the fixed timestamp.
    - `SleepFunction`is a `sleep()` implementation, which doesn't halt but increases an `Increment`e.g. a `time()` mock.
    - `UsleepFunction`is an `usleep()` implementation, which doesn't halt but increases an `Increment` e.g. a `microtime()` mock.
- `MockBuilder::build()`builds a `Mock` object.

After you have build your `Mock` object you have to call `enable()`to enable the mock in the given namespace. When you are finished with that mock you should disable it by calling `disable()`on the mock instance.

This example illustrates mocking of the unqualified function `time()` in the namespace `foo`:

```
namespace foo;

use phpmock\MockBuilder;

$builder = new MockBuilder();
$builder->setNamespace(__NAMESPACE__)
    ->setName("time")
    ->setFunction(
        function () {
            return 1417011228;
        }
    );

$mock = $builder->build();

// The mock is not enabled yet.
assert (time() != 1417011228);

$mock->enable();
assert (time() == 1417011228);

// The mock is disabled and PHP's built-in time() is called.
$mock->disable();
assert (time() != 1417011228);
```

Instead of setting the mock function with `MockBuilder::setFunction()` you could also use the existing `FixedValue`:

```
namespace foo;

use Kartavik\PHPMock\MockBuilder;
use Kartavik\PHPMock\Functions\FixedValue;

$builder = new MockBuilder();
$builder->setNamespace(__NAMESPACE__)
    ->setName("time")
    ->setFunctionProvider(new FixedValueFunction(1417011228));

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

### Reset global state

[](#reset-global-state)

An enabled mock changes global state. This will break subsequent tests if they run code which would call the mock unintentionally. Therefore you should always disable a mock after the test case. You will have to disable the created mock. You could do this for all mocks by calling the static method `Mock::disableAll()`.

### Mock environments

[](#mock-environments)

Complex mock environments of several mocked functions can be grouped in a `Environment\Mock`:

- `Environment\Mock::enable()`enables all mocked functions of this environment.
- `Environment\Mock::disable()`disables all mocked functions of this environment.
- `Environment\Mock::define()`defines all mocked functions of this environment.

#### SleepEnvironmentBuilder

[](#sleepenvironmentbuilder)

The `Environment\SleepBuilder`builds a mock environment where `sleep()` and `usleep()` return immediatly. Furthermore they increase the amount of time in the mocked `date()`, `time()` and `microtime()`:

```
namespace foo;

use Kartavik\Environment\SleepBuilder;

$builder = new SleepEnvironmentBuilder();
$builder->addNamespace(__NAMESPACE__)
    ->setTimestamp(1417011228);

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

// This won't delay the test for 10 seconds, but increase time().
sleep(10);

assert(1417011228 + 10 == time());
```

If the mocked functions should be in different namespaces you can add more namespaces with [`Environment\SleepBuilder::addNamespace()`](http://php-mock.github.io/php-mock/api/class-phpmock.environment.SleepEnvironmentBuilder.html#_addNamespace)

Authors and contributors
========================

[](#authors-and-contributors)

Fork contributor - [Roman Vakura](mailto:roman.varkuta@gmail.com)

Author - this project is fork of [php-mock/php-mock](https://github.com/php-mock/php-mock)

License
=======

[](#license)

- [WTFPL](./LICENSE)

###  Health Score

29

—

LowBetter than 59% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity7

Limited adoption so far

Community16

Small or concentrated contributor base

Maturity66

Established project with proven stability

 Bus Factor1

Top contributor holds 87.4% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~110 days

Recently: every ~302 days

Total

15

Last Release

2642d ago

Major Versions

0.1.1 → 1.0.02015-10-26

1.0.1 → 2.0.02017-02-17

2.0.0 → 3.0.02019-02-18

PHP version history (5 changes)0.1PHP &gt;=5.3

0.2PHP &gt;=5.4

1.0.0PHP &gt;=5.5

2.0.0PHP &gt;=5.6

3.0.0PHP ^7.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/9695eb1f105a8ff23e38b62bc46bb472d001a809dff1a69cec415d95421652b3?d=identicon)[KartaviK](/maintainers/KartaviK)

---

Top Contributors

[![malkusch](https://avatars.githubusercontent.com/u/1623984?v=4)](https://github.com/malkusch "malkusch (125 commits)")[![KartaviK](https://avatars.githubusercontent.com/u/5941637?v=4)](https://github.com/KartaviK "KartaviK (9 commits)")[![michalbundyra](https://avatars.githubusercontent.com/u/7423207?v=4)](https://github.com/michalbundyra "michalbundyra (3 commits)")[![geoffroy-aubry](https://avatars.githubusercontent.com/u/1247448?v=4)](https://github.com/geoffroy-aubry "geoffroy-aubry (2 commits)")[![OndraM](https://avatars.githubusercontent.com/u/793041?v=4)](https://github.com/OndraM "OndraM (1 commits)")[![heiglandreas](https://avatars.githubusercontent.com/u/91998?v=4)](https://github.com/heiglandreas "heiglandreas (1 commits)")[![joshk](https://avatars.githubusercontent.com/u/8701?v=4)](https://github.com/joshk "joshk (1 commits)")[![edhgoose](https://avatars.githubusercontent.com/u/1108173?v=4)](https://github.com/edhgoose "edhgoose (1 commits)")

---

Tags

testBDDTDDmockstubtest doublefunction

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

![Health badge](/badges/kartavik-php-mock/health.svg)

```
[![Health](https://phpackages.com/badges/kartavik-php-mock/health.svg)](https://phpackages.com/packages/kartavik-php-mock)
```

###  Alternatives

[mockery/mockery

Mockery is a simple yet flexible PHP mock object framework

10.7k497.0M23.6k](/packages/mockery-mockery)[php-mock/php-mock

PHP-Mock can mock built-in PHP functions (e.g. time()). PHP-Mock relies on PHP's namespace fallback policy. No further extension is needed.

36918.1M98](/packages/php-mock-php-mock)[php-mock/php-mock-phpunit

Mock built-in PHP functions (e.g. time()) with PHPUnit. This package relies on PHP's namespace fallback policy. No further extension is needed.

1718.2M399](/packages/php-mock-php-mock-phpunit)[php-mock/php-mock-integration

Integration package for PHP-Mock

1410.5M3](/packages/php-mock-php-mock-integration)[php-mock/php-mock-mockery

Mock built-in PHP functions (e.g. time()) with Mockery. This package relies on PHP's namespace fallback policy. No further extension is needed.

392.1M96](/packages/php-mock-php-mock-mockery)[php-mock/php-mock-prophecy

Mock built-in PHP functions (e.g. time()) with Prophecy. This package relies on PHP's namespace fallback policy. No further extension is needed.

16496.6k15](/packages/php-mock-php-mock-prophecy)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
