Strict mode¶
This guide shows how to turn on opt-in validation for mocked method names and handle dynamic methods in your test suite.
Turn on strict mocked method checks¶
By default, friendsofmago/mago-mockery does not check whether a literal method name passed to shouldReceive() exists on the mocked class.
To turn the check on in mago.toml, set MAGO_MOCKERY_STRICT_METHODS = "1" under [extension-hosts.mockery] environment:
[extension-hosts.mockery]
command = ["php", "-d", "xdebug.mode=off", "-d", "pcov.enabled=0", "-d", "memory_limit=512M", "vendor/bin/mago-mockery-worker"]
workers = 1
environment = { MAGO_MOCKERY_STRICT_METHODS = "1" }
Accepted truthy values are 1, true, yes, and on, trimmed and case-insensitive.
If you run a custom worker with MockeryExtension::plugins(), pass strictMockedMethods: true instead of setting the environment variable:
MockeryExtension::plugins(strictMockedMethods: true);
Run the analyzer¶
Run mago analyze to check your tests:
vendor/bin/mago analyze
Mago reports mockery/unknown-mocked-method at error level for any literal or higher-order method name that does not exist on the mocked class.
$mock = Mockery::mock(Greeter::class);
$mock->shouldReceive('doesNotExist'); // mockery/unknown-mocked-method
$mock->shouldReceive()->doesNotExist(); // mockery/unknown-mocked-method
Allow intentional dynamic methods¶
If a test intentionally mocks a method that the class does not declare, call shouldAllowMockingMethod() on the same mock before the expectation:
$mock = Mockery::mock(Greeter::class);
$mock->shouldAllowMockingMethod('dynamicMethod');
$mock->shouldReceive('dynamicMethod')->andReturn('ok');
Follow these rules so StrictAllowanceResolver recognizes the allowance:
- Call
shouldAllowMockingMethod()on the same mock identity, either the same local variable or a straight-line$this->property. - Keep the allowance on every path to the expectation. A reassignment, an
unset()call, a$thisalias, a by-reference pass, or an unmerged branch clears the allowance.
Silence individual calls or legacy paths¶
To silence a single call without calling shouldAllowMockingMethod(), add an inline Mago ignore comment above the call:
// @mago-ignore analysis:mockery/unknown-mocked-method
$mock->shouldReceive('handledExternally');
To adopt strict mode without checking older test directories, add a scoped ignore entry in mago.toml:
[analyzer]
ignore = [
{ code = "mockery/unknown-mocked-method", in = "tests/Legacy/" },
]
See Diagnostics for the exact list of checked calls and automatic exclusions.