PHPackages                             ernestmarcinko/mockutils - 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. ernestmarcinko/mockutils

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

ernestmarcinko/mockutils
========================

PHPUnit test mocking utility tools

1.0.3(1y ago)0121↓100%MITPHPPHP ^8.3

Since Mar 27Pushed 1y ago1 watchersCompare

[ Source](https://github.com/ernestmarcinko/mockutils)[ Packagist](https://packagist.org/packages/ernestmarcinko/mockutils)[ Docs](https://github.com/ernestmarcinko/mockutils)[ RSS](/packages/ernestmarcinko-mockutils/feed)WikiDiscussions master Synced today

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

Mock Utility tools for PHPUnit TestCase
=======================================

[](#mock-utility-tools-for-phpunit-testcase)

[![tests](https://github.com/ernestmarcinko/mockutils/actions/workflows/tests.yml/badge.svg)](https://github.com/ernestmarcinko/mockutils/actions/workflows/tests.yml/badge.svg)

This package provides ome utility functions for PHPUnit TestCase class (and descendants) via the `MockUtils` trait:

- [Global Mocks](#global-mocks) - `setGlobalMocks()` &amp; `unsetGlobalMocks()` methods to set global function mocks within a namespace
- [Exception assertion](#exception-assertion) - via `expectCatchException()` - Method similar to expectException(), but without terminating the test execution

Installation &amp; Inclusion
----------------------------

[](#installation--inclusion)

To install the package:

```
composer require ernestmarcinko/mockutils --dev
```

### Including in your tests

[](#including-in-your-tests)

There are two ways, one is using a trait to extend your TestCase functionality (recommended):

```
use ErnestMarcinko\MockUtils\MockUtils;
use PHPUnit\Framework\TestCase;

class MyTest extends TestCase {
	use MockUtils;
	...
}
```

..or use the MockUtilsTestCase class instead of TestCase:

```
use ErnestMarcinko\MockUtils\MockUtilsTestCase;

class MyTest extends MockUtilsTestCase {
	...
}
```

`MockUtilsTestCase` is only an empty class extending `TestCase` and using `MockUtils`.

Global Mocks
------------

[](#global-mocks)

The trait adds two utility functions to `setGlobalMocks()` and `unsetGlobalMocks()` to set and unset global mocks.

### setGlobalMocks

[](#setglobalmocks)

```
protected function setGlobalMocks(array $global_mocks, ?string $namespace): void
```

Sets global mocks to the given namespace.

#### Parameters

[](#parameters)

ParamTypeDescriptionRequiredExtra info`$global_mocks``array`Array of global function name and return value or callabletrue`$namespace``string`The namespace of the code where the global function should be setfalseMake sure to use the code namespace, not the test code namespace#### Example

[](#example)

Say you have a service, which uses `curl_exec` to get a response from an API. During testing you want to mock it and avoid actual connection to the API and instead test with pre-defined responses.

```
namespace MyNamespace\MySubNamespace;

class MyClass {
	public function handler() {
		//....

		$response = curl_exec($curl); // you want to mock this

		//You do something with $response below
	}
}
```

In the test we need the curl\_exec to return 'response' for the mock, to do that:

```
namespace MyTestNamespace;

class TestMyClass {
	public function testHandler() {
		$this->setGlobalMocks(
			[
				'curl_exec' => 'response'
			],
			'MyNamespace\\MySubNamespace'
		)

		$o = new MyClass();
		$this->assertSame( 'expected output', $o->handler() );
	}
}
```

It's also possible to define a callable instead of a static response:

```
namespace MyTestNamespace;

class TestMyClass {
	public function testHandler() {
		$this->setGlobalMocks(
			[
				'curl_exec' => function($curl) {
					return 'response';
				}
			],
			'MyNamespace\\MySubNamespace'
		)

		$o = new MyClass();
		$this->assertSame( 'expected output', $o->handler() );
	}
}
```

### unsetGlobalMocks

[](#unsetglobalmocks)

```
protected function unsetGlobalMocks(?array $global_mocks=null): void
```

Unsets the given global mocks or all global mocks previously defined.

#### Parameters

[](#parameters-1)

ParamTypeDescriptionRequiredExtra info`$global_mocks``array`Array of global function namesfalse#### Examples

[](#examples)

```
namespace MyTestNamespace;

class TestMyClass {
	public function testHandler() {
		$this->setGlobalMocks(
			[
				'time' => fn()=>time()-3600,
				'json_decode' => array(),
				'strval' => fn($v)=>$v,
			],
			'MyNamespace\\MySubNamespace'
		)
		$o = new MyClass();
		$this->assertSame( 'expected output 1', $o->handler() );

		$this->unsetGlobalMocks(array('time')); // unset just the time mock
		$this->assertSame( 'expected output 2', $o->handler() );

		$this->unsetGlobalMocks(); // unset all remaining mocks
		$this->assertSame( 'expected output 3', $o->handler() );
	}
}
```

Exception Assertion
-------------------

[](#exception-assertion)

### expectCatchException

[](#expectcatchexception)

Checks if the exception was thrown **without** execution termination.

```
protected function expectCatchException(callable $fn, string $throwable, ?string $message = null): void
```

Compared to PHPUnit core `TestCase::expectException` this function will not terminate the test execution. The function to test must be however passed in as a closure, ex.: `expectCatchException(fn()=>$o->myMethod(), ...)`

#### Parameters

[](#parameters-2)

ParamTypeDescriptionRequiredExtra info`$fn``callable`Function to testtrueUse closure `fn()=>{$myObj->myMethod();}` to pass in any method`$throwable``class-string`Expected exception class nametrue`$message``string`The expected error messagefalse(optional) If set, then the function will also check the Exception message.#### Return values

[](#return-values)

The function is void, does not return anything, however:

> `expectCatchException` will trigger `TestCase::fail()` if no exception was thrown, or any of the criteria was not met.

#### Example

[](#example-1)

```
namespace MyTestNamespace;

class TestMyClass {
	public function testHandler() {
		$this->expectCatchException(function(){
			throw new Exception('hey!');
		}, Exception::class);

		// Execution continues

		$this->expectCatchException(function(){
			throw new Exception('hey!');
		}, Exception::class, 'hey!');

		$o = new MyClass();
		$this->expectCatchException(fn()=>$o->handle(), Exception::class);

		$this->expectCatchException(
			fn()=>$o->handle(),
			Exception::class,
			'Exception message!'
		);
	}
}
```

###  Health Score

30

—

LowBetter than 67% of packages

Maintenance31

Infrequent updates — may be unmaintained

Popularity12

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity59

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

4

Last Release

724d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/7a5350ad4c50539ec94ffa30c01f3174f4e7d4903559328a74e361aabbdf2a75?d=identicon)[ernestmarcinko](/maintainers/ernestmarcinko)

---

Top Contributors

[![ernestmarcinko](https://avatars.githubusercontent.com/u/6159897?v=4)](https://github.com/ernestmarcinko "ernestmarcinko (15 commits)")

---

Tags

testingphpunittestmockutlis

###  Code Quality

Static AnalysisPHPStan

Code StylePHP\_CodeSniffer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/ernestmarcinko-mockutils/health.svg)

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

###  Alternatives

[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.0M353](/packages/php-mock-php-mock-phpunit)[ta-tikoma/phpunit-architecture-test

Methods for testing application architecture

10642.5M11](/packages/ta-tikoma-phpunit-architecture-test)[blastcloud/guzzler

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

272408.6k29](/packages/blastcloud-guzzler)[fr3d/swagger-assertions

Test your API requests and responses against your swagger definition

138840.4k5](/packages/fr3d-swagger-assertions)[elliotchance/concise

Concise is test framework for using plain English and minimal code, built on PHPUnit.

47223.6k3](/packages/elliotchance-concise)[lastzero/test-tools

Increases testing productivity by adding a service container and self-initializing fakes to PHPUnit

2244.0k13](/packages/lastzero-test-tools)

PHPackages © 2026

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