PHPackages                             yguedidi/global-functions-mocker - 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. yguedidi/global-functions-mocker

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

yguedidi/global-functions-mocker
================================

A simple class that allow you mock global functions.

19[1 issues](https://github.com/yguedidi/global-functions-mocker/issues)PHP

Since Sep 17Pushed 11y ago1 watchersCompare

[ Source](https://github.com/yguedidi/global-functions-mocker)[ Packagist](https://packagist.org/packages/yguedidi/global-functions-mocker)[ RSS](/packages/yguedidi-global-functions-mocker/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

Global Functions Mocker
=======================

[](#global-functions-mocker)

A simple class that allow you mock global functions for your unit tests.

**Note**: This works only if you don't use absolute function calls (like `\phpversion()`) in your classes.

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

[](#installation)

Add `yguedidi/global-functions-mocker` to the `require-dev` section of your `composer.json`

```
{
    "require-dev": {
        "yguedidi/global-functions-mocker": "*"
    }
}
```

Basic usage
-----------

[](#basic-usage)

### 0 - Prerequisites

[](#0---prerequisites)

- [PHPUnit](http://phpunit.de/)
- [Mockery](https://github.com/padraic/mockery)

### 1 - Setup

[](#1---setup)

First of all, call the `GlobalFunctionsMocker::setUp()` method in your test `setUp()` method.
This is needed to clear mocked global functions between tests.

### 2 - Namespaced function

[](#2---namespaced-function)

Create a function named **exactly** like the global function in the namespace of your tested class, but define it in your test file.
The body of that function should be:

```
return GlobalFunctionsMocker::execute('global_function_name', func_get_args());
```

### 3 - Mock the function

[](#3---mock-the-function)

Then just mock the global function you need in your tests with `GlobalFunctionsMocker::mock('global_function_name')`.
It returns a subset of [Mockery\\Expectation](https://github.com/padraic/mockery/blob/master/library/Mockery/Expectation.php) so you can define some expectations: [MockedFunction](src/MockedFunction.php)

Full exemple
------------

[](#full-exemple)

This exemple assume your tested class and your unit test class are in different namespace.

```
// src/FooClass.php
namespace Acme\FooClass;

class FooClass {
    public function foo()
    {
        return phpversion();
    }
}
```

```
// tests/FooClassTest.php

// Note the different namespace
namespace Acme\Tests\FooClass
{
    use Acme\FooClass;
    use YassineGuedidi\GlobalFunctionsMocker\GlobalFunctionsMocker as GFM;

    class FooClassTest extends \PHPUnit_Framework_TestCase
    {
        protected function setUp()
        {
            GFM::setUp()
        }

        public function testFoo()
        {
            GFM::mock('phpversion')->once()->withNoArgs()->andReturn('foo');
            $object = new FooClass();
            $this->assertEquals('foo', $object->foo());
        }
    }
}

// IMPORTANT: Define the function in the tested class namespace
namespace Acme\FooClass
{
    use YassineGuedidi\GlobalFunctionsMocker\GlobalFunctionsMocker as GFM;

    function phpversion()
    {
        // Don't forget 'func_get_args()' for fallback to the real global function work
        return GFM::execute('phpversion', func_get_args());
    }
}
```

Reference
---------

[](#reference)

#### GlobalFunctionsMocker::mock($functionName)

[](#globalfunctionsmockermockfunctionname)

Mock a global function. Should be called in your tests.

- **$functionName**
    Name of the global function to mock

#### GlobalFunctionsMocker::execute($functionName, $args)

[](#globalfunctionsmockerexecutefunctionname-args)

Execute a mocked global function. Call this in your namespaced global function definition.

- **$functionName**
    Name of the global function to execute
- *$args* (optional)
    Arguments passed to the global function (empty array by default).
    **Important**: This should be `func_get_args()` in the namespaced function. It allow fallback to the real global if it's not mocked.

It will fallback to the real global function if the function isn't mocked by a test, or if you mock it with some expectations but without a return value.

And if the real global function is not define (missing PHP extension for exemple), it will gracefully throw a `PHPUnit_Framework_SkippedTestError` exception that will skip the current test with a useful message.

#### MockedFunction

[](#mockedfunction)

Available functions: with(), withArgs(), withNoArgs(), withAnyArgs(), andReturn(), andReturnValues(), andReturnUsing() andReturnUndefined(), andReturnNull(), andThrow(),andThrowExceptions(), zeroOrMoreTimes(), times(), never(), once(), twice(), atLeast(), atMost(), between().

Look at Mockery's documentation about [Expectation Declarations](http://docs.mockery.io/en/latest/reference/expectations.html) and [Argument Validation](http://docs.mockery.io/en/latest/reference/argument_validation.html) for more detail.

License
-------

[](#license)

See [LICENSE file](LICENSE)

###  Health Score

15

—

LowBetter than 3% of packages

Maintenance0

Infrequent updates — may be unmaintained

Popularity6

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity41

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.

### Community

Maintainers

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

---

Top Contributors

[![yguedidi](https://avatars.githubusercontent.com/u/1480128?v=4)](https://github.com/yguedidi "yguedidi (2 commits)")

### Embed Badge

![Health badge](/badges/yguedidi-global-functions-mocker/health.svg)

```
[![Health](https://phpackages.com/badges/yguedidi-global-functions-mocker/health.svg)](https://phpackages.com/packages/yguedidi-global-functions-mocker)
```

###  Alternatives

[phpspec/prophecy

Highly opinionated mocking framework for PHP 5.3+

8.5k551.7M682](/packages/phpspec-prophecy)[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)[phpspec/phpspec

Specification-oriented BDD framework for PHP 7.1+

1.9k36.7M3.1k](/packages/phpspec-phpspec)

PHPackages © 2026

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