PHPackages                             mintyphp/mocking - 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. mintyphp/mocking

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

mintyphp/mocking
================

v2.0.1(6mo ago)2511MITPHPPHP &gt;=7.4

Since Nov 16Pushed 6mo agoCompare

[ Source](https://github.com/mintyphp/mocking)[ Packagist](https://packagist.org/packages/mintyphp/mocking)[ RSS](/packages/mintyphp-mocking/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (8)Dependencies (2)Versions (9)Used By (1)

MintyPHP Mocking
================

[](#mintyphp-mocking)

Lightweight utilities to mock static methods and built-in functions in PHP unit tests without invasive refactors.

This library works by:

- Intercepting class autoload for specific classes to provide a stub that forwards static calls to your expectations
- Defining namespaced functions on the fly so unqualified function calls (like `microtime()`) in that namespace are routed through your mock

It’s intentionally small, explicit, and easy to reason about. I wrote a [blog article](https://www.tqdev.com/2025-mocking-static-methods-built-in-functions-php/) with some background information.

Requirements
------------

[](#requirements)

- PHP 7.4+
- PHPUnit

Installation
------------

[](#installation)

Add as a dev dependency with Composer:

```
composer require --dev mintyphp/mocking
```

Ensure Composer’s autoloader is required in your test bootstrap (PHPUnit usually does this for you).

Mocking static methods
----------------------

[](#mocking-static-methods)

Contract:

- You register a mock for a fully-qualified class name before that class is loaded the first time in the process
- You declare one or more ordered expectations: method name, exact argument list, optional return value or exception
- Each static call consumes the next expectation and either returns the value or throws the exception
- Any leftover expectations cause a test failure when you assert

Example (taken from `tests/StaticMethodMockTest.php`):

```
use MintyPHP\Mocking\StaticMethodMock;
use MintyPHP\Mocking\Tests\Math\Adder; // Class with a static method we want to mock
use PHPUnit\Framework\TestCase;

class MyTest extends TestCase
{
    public function test_add(): void
    {
        // 1) Register the mock (before Adder is ever loaded)
        $mock = new StaticMethodMock(Adder::class, $this);

        // 2) Declare expectations in order
        $mock->expect('add', [1, 2], 3);

        // 3) Exercise the code under test
        $result = Adder::add(1, 2);

        // 4) Assert and verify expectations were fully consumed
        $this->assertSame(3, $result);
        $mock->assertExpectationsMet();
    }
}
```

Notes and caveats:

- Ordering matters: expectations are matched and consumed in FIFO order
- Method name is compared case-insensitively; arguments use PHPUnit’s assertEquals comparison
- If you call more times than you declared, the next call fails with "No expectations left …"
- If you declared more expectations than were consumed, `assertExpectationsMet()` fails and lists how many remain
- The mock wins the autoload race by registering a prepended autoloader; it only works if the real class has not already been defined earlier in the process

Throwing instead of returning:

```
$mock->expect('danger', ['x'], null, new \RuntimeException('boom'));
// Calling Adder::danger('x') will throw that exception
```

Mocking built-in functions
--------------------------

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

Contract:

- You register a mock for the namespace where the function is called from
- You declare one or more ordered expectations: function name, exact argument list, optional return value or exception
- The library defines a function in that namespace (once) that forwards calls to your expectations

Example (taken from `tests/BuiltInFunctionMockTest.php`):

```
use MintyPHP\Mocking\BuiltInFunctionMock;
use MintyPHP\Mocking\Tests\Time\StopWatch; // Calls microtime() inside its own namespace
use PHPUnit\Framework\TestCase;

class MyTest extends TestCase
{
    public function test_stopwatch(): void
    {
        // 1) Register the mock for the namespace where StopWatch lives
        $mock = new BuiltInFunctionMock('MintyPHP\\Mocking\\Tests\\Time', $this);

        // 2) microtime(true) will be called twice; set exact expectations
        $mock->expect('microtime', [true], 1763333612.602);
        $mock->expect('microtime', [true], 1763333614.825);

        // 3) Exercise the code under test
        $sw = new StopWatch();
        $sw->start();
        $elapsedMs = $sw->stop();

        $this->assertSame(2223, $elapsedMs);
        $mock->assertExpectationsMet();
    }
}
```

Notes and caveats:

- This only intercepts unqualified calls within the targeted namespace, e.g. `microtime()` inside `MintyPHP\Mocking\Tests\Time`
- Fully-qualified calls like `\microtime()` or calls imported with `use function` that point to another namespace will NOT be intercepted
- Ordering and argument comparison rules are the same as for static method mocks

Throwing instead of returning:

```
$mock = new BuiltInFunctionMock('App\\Service', $this);
$mock->expect('file_get_contents', ['https://example.com'], null, new \RuntimeException('network error'));
```

Good to know
------------

[](#good-to-know)

- Keep your mock registration close to the start of your test so it runs before the real class is autoloaded or the function is first called
- Expectations are per-mock-instance; each instance tracks and asserts its own queue
- Internals use `eval()` to define tiny proxy classes/functions during tests; this library is intended for test environments only

Run the test suite
------------------

[](#run-the-test-suite)

From the project root:

```
./vendor/bin/phpunit
```

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

[](#alternatives)

The following libraries are recommended to explore as (better) alternatives:

- [php-mock/php-mock](https://www.github.com/php-mock/php-mock)
- [mockery/mockery](https://www.github.com/mockery/mockery)
- [php-mock/php-mock-phpunit](https://www.github.com/php-mock/php-mock-phpunit)

###  Health Score

35

—

LowBetter than 79% of packages

Maintenance69

Regular maintenance activity

Popularity14

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity40

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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 ~0 days

Total

8

Last Release

180d ago

Major Versions

v1.1.2 → v2.0.02025-11-16

### Community

Maintainers

![](https://www.gravatar.com/avatar/eb92d699fb8e724c9a9091ee7182737ffdb5e392a8e137391d102aa8fda8de7b?d=identicon)[mevdschee](/maintainers/mevdschee)

---

Top Contributors

[![mevdschee](https://avatars.githubusercontent.com/u/1288217?v=4)](https://github.com/mevdschee "mevdschee (44 commits)")

---

Tags

builtin-functionsmockphpphp-mockingphpunittest-doubles

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/mintyphp-mocking/health.svg)

```
[![Health](https://phpackages.com/badges/mintyphp-mocking/health.svg)](https://phpackages.com/packages/mintyphp-mocking)
```

###  Alternatives

[phpspec/prophecy

Highly opinionated mocking framework for PHP 5.3+

8.5k551.7M682](/packages/phpspec-prophecy)[vimeo/psalm

A static analysis tool for finding errors in PHP applications

5.8k77.5M6.7k](/packages/vimeo-psalm)[brianium/paratest

Parallel testing for PHP

2.5k118.8M754](/packages/brianium-paratest)[beberlei/assert

Thin assertion library for input validation in business models.

2.4k96.9M570](/packages/beberlei-assert)[mikey179/vfsstream

Virtual file system to mock the real file system in unit tests.

1.4k108.0M2.7k](/packages/mikey179-vfsstream)[orchestra/testbench

Laravel Testing Helper for Packages Development

2.2k39.1M32.1k](/packages/orchestra-testbench)

PHPackages © 2026

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