| FazBrowse GitHub Viewer | Trending | | Home |
| Tools: [Download Repo ZIP] [Original HTTPS Page] |
| Name | Name | Last commit date | ||
|---|---|---|---|---|
Lightweight utilities to mock static methods and built-in functions in PHP unit tests without invasive refactors.
This library works by:
It’s intentionally small, explicit, and easy to reason about. I wrote a blog article with some background information.
Add as a dev dependency with Composer:
composer require --dev mintyphp/mockingEnsure Composer’s autoloader is required in your test bootstrap (PHPUnit usually does this for you).
Contract:
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:
Throwing instead of returning:
$mock->expect('danger', ['x'], null, new \RuntimeException('boom'));
// Calling Adder::danger('x') will throw that exceptionContract:
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:
Throwing instead of returning:
$mock = new BuiltInFunctionMock('App\\Service', $this);
$mock->expect('file_get_contents', ['https://example.com'], null, new \RuntimeException('network error'));From the project root:
./vendor/bin/phpunitThe following libraries are recommended to explore as (better) alternatives:
| Back | FazBrowse Home | New Git URL |