PHPackages                             kenjis/monkey-patch - 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. kenjis/monkey-patch

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

kenjis/monkey-patch
===================

Monkey patching for exit(), functions, methods, and constants

v1.0.1(4y ago)618.9k—6.7%2[4 issues](https://github.com/kenjis/monkey-patch/issues)[2 PRs](https://github.com/kenjis/monkey-patch/pulls)MITPHPPHP ^7.3 || ^8.0

Since Mar 5Pushed 1y ago1 watchersCompare

[ Source](https://github.com/kenjis/monkey-patch)[ Packagist](https://packagist.org/packages/kenjis/monkey-patch)[ Docs](https://github.com/kenjis/monkey-patch)[ RSS](/packages/kenjis-monkey-patch/feed)WikiDiscussions 1.x Synced 1mo ago

READMEChangelog (2)Dependencies (4)Versions (4)Used By (0)

Monkey Patch
============

[](#monkey-patch)

This package is a standalone package of [ci-phpunit-test](https://github.com/kenjis/ci-phpunit-test) 's Monkey Patching.

This provides four monkey patchers.

- `ExitPatcher`: Converts `exit()` to Exception
- `FunctionPatcher`: Patches Functions
- `MethodPatcher`: Patches Methods in User-defined Classes
- `ConstantPatcher`: Changes Constant Values

Table of Contents
-----------------

[](#table-of-contents)

- [Requirements](#requirements)
- [Installation](#installation)
- [Usage](#usage)
    - [Configure](#configure)
    - [Convert `exit()` to Exception](#convert-exit-to-exception)
    - [Patch Functions](#patch-functions)
        - [Change Return Value](#change-return-value)
        - [Patch Other Functions](#patch-other-functions)
    - [Patch Methods in User-defined Classes](#patch-methods-in-user-defined-classes)
    - [Patch Constants](#patch-constants)
- [Class Reference](#class-reference)
- [License](#license)

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

[](#requirements)

- PHP 7.3 or later

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

[](#installation)

```
$ composer require --dev kenjis/monkey-patch
```

Usage
-----

[](#usage)

**Note:** The line number when an error occurs is probably different from the actual source code. Please check the cache file of the source that Monkey Patching creates.

**Note:** Using this package has a negative impact on speed of tests.

### Configure

[](#configure)

- To enable monkey patching, add [the content of the bootstrap](https://github.com/kenjis/monkey-patch/blob/1.x/src/bootstrap.php) in your PHPUnit bootstrap file.
    - Set [MonkeyPatchManager::init()](https://github.com/kenjis/monkey-patch/blob/f5b1839a01c0c3cd56f4873e8c307b0583a5526b/src/bootstrap.php#L31-L61) arguments.
- To verify invocations, use the [MonkeyPatchTrait](https://github.com/kenjis/monkey-patch/blob/1.x/src/Traits/MonkeyPatchTrait.php) in your TestCase class.

### Convert `exit()` to Exception

[](#convert-exit-to-exception)

This patcher converts `exit()` or `die()` statements to exceptions on the fly.

If you have a controller like below:

```
    public function index()
    {
        $this->output
            ->set_status_header(200)
            ->set_content_type('application/json', 'utf-8')
            ->set_output(json_encode(['foo' => 'bar']))
            ->_display();
        exit();
    }
```

A test case could be like this:

```
    public function test_index()
    {
        try {
            $this->request('GET', 'welcome/index');
        } catch (ExitException $e) {
            $output = ob_get_clean();
        }

        $this->assertContains('{"foo":"bar"}', $output);
    }
```

### Patch Functions

[](#patch-functions)

This patcher allows replacement of global functions that can't be mocked by PHPUnit.

But it has a few limitations. Some functions can't be replaced and it might cause errors.

So by default we can replace only a dozen pre-defined functions in [FunctionPatcher](https://github.com/kenjis/monkey-patch/blob/a11e1f227234dadeae2460d29b9c8ca6e91c88de/src/Patcher/FunctionPatcher.php#L31-L49).

```
    public function test_index()
    {
        MonkeyPatch::patchFunction('mt_rand', 100, 'Welcome::index');

        $output = $this->request('GET', 'welcome/index');

        $this->assertContains('100', $output);
    }
```

`MonkeyPatch::patchFunction()` replaces PHP native function `mt_rand()` in `Welcome::index` method, and it will return `100` in the test method.

**Note:** If you call `MonkeyPatch::patchFunction()` without 3rd argument, all the functions (located in `include_paths` and not in `exclude_paths`) called in the test method will be replaced. So, for example, a function in your library code might be replaced, and it results in an unexpected outcome.

#### Change Return Value

[](#change-return-value)

You could change return value of patched function using PHP closure:

```
        MonkeyPatch::patchFunction(
            'function_exists',
            function ($function) {
                if ($function === 'random_bytes') {
                    return true;
                } elseif ($function === 'openssl_random_pseudo_bytes') {
                    return false;
                } elseif ($function === 'mcrypt_create_iv') {
                    return false;
                } else {
                    return __GO_TO_ORIG__;
                }
            },
            Welcome::class
        );
```

#### Patch Other Functions

[](#patch-other-functions)

If you want to patch other functions, you can add them to [functions\_to\_patch](https://github.com/kenjis/monkey-patch/blob/a11e1f227234dadeae2460d29b9c8ca6e91c88de/src/bootstrap.php#L56-L59) in `MonkeyPatchManager::init()`.

But there are a few known limitations:

- Patched functions which have parameters called by reference don't work.
- You may see visibility errors if you pass non-public callbacks to patched functions. For example, you pass `[$this, 'method']` to `array_map()` and the `method()` method in the class is not public.

### Patch Methods in User-defined Classes

[](#patch-methods-in-user-defined-classes)

This patcher allows replacement of methods in user-defined classes.

```
    public function test_index()
    {
        MonkeyPatch::patchMethod(
            Category_model::class,
            ['get_category_list' => [(object) ['name' => 'Nothing']]]
        );

        $output = $this->request('GET', 'welcome/index');

        $this->assertContains('Nothing', $output);
    }
```

`MonkeyPatch::patchMethod()` replaces `get_category_list()` method in `Category_model`, and it will return `[(object) ['name' => 'Nothing']]` in the test method.

### Patch Constants

[](#patch-constants)

This patcher allows replacement of constant value.

```
    public function test_index()
    {
        MonkeyPatch::patchConstant(
            'ENVIRONMENT',
            'development',
            Welcome::class . '::index'
        );

        $output = $this->request('GET', 'welcome/index');

        $this->assertContains('development', $output);
    }
```

`MonkeyPatch::patchConstant()` replaces the return value of the constant `ENVIRONMENT` in `Welcome::index` method.

There are a few known limitations:

- Cannot patch constants that are used as default values in function arguments.
- Cannot patch constants that are used as default values in constant declarations.
- Cannot patch constants that are used as default values in property declarations.
- Cannot patch constants that are used as default values in static variable declarations.

Class Reference
---------------

[](#class-reference)

See [ci-phpunit-test docs](https://github.com/kenjis/ci-phpunit-test/blob/3.x/docs/FunctionAndClassReference.md#class-monkeypatch).

License
-------

[](#license)

This package is licensed using the MIT License.

Please have a look at [`LICENSE`](LICENSE).

###  Health Score

33

—

LowBetter than 75% of packages

Maintenance14

Infrequent updates — may be unmaintained

Popularity33

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity60

Established project with proven stability

 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 ~66 days

Total

3

Last Release

1769d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/220fcd79c66bd061265dfe8d29cc640250616c4719dfb31f4ab87a1af101dc65?d=identicon)[kenjis](/maintainers/kenjis)

---

Top Contributors

[![kenjis](https://avatars.githubusercontent.com/u/87955?v=4)](https://github.com/kenjis "kenjis (130 commits)")

---

Tags

hacktoberfestmonkey-patchmonkey-patchingphpunittestingtestingphpunitmockMonkey Patchingmonkey patch

### Embed Badge

![Health badge](/badges/kenjis-monkey-patch/health.svg)

```
[![Health](https://phpackages.com/badges/kenjis-monkey-patch/health.svg)](https://phpackages.com/packages/kenjis-monkey-patch)
```

###  Alternatives

[brianium/paratest

Parallel testing for PHP

2.5k118.8M754](/packages/brianium-paratest)[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)[kahlan/kahlan

The PHP Test Framework for Freedom, Truth and Justice.

1.2k1.2M247](/packages/kahlan-kahlan)[brain/monkey

Mocking utility for PHP functions and WordPress plugin API

33412.5M350](/packages/brain-monkey)[ta-tikoma/phpunit-architecture-test

Methods for testing application architecture

10745.9M13](/packages/ta-tikoma-phpunit-architecture-test)[blastcloud/guzzler

Supercharge your app or SDK with a testing library specifically for Guzzle.

272419.3k35](/packages/blastcloud-guzzler)

PHPackages © 2026

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