I'm trying to write a PHPUnit test using Mockery, and I keep running into issues when using the null coalescing operator (??) with mocked properties. Specifically, ?? seems to always return null, which causes the ?? operator to fall back to the default value, even though the property is mocked correctly and returns a value. Here’s a simplified version of my setup:
public function testExample()
{
$model = Mockery::mock(Model::class)->shouldIgnoreMissing();
// Mocking a property
$model->shouldReceive('getAttribute')
->with('title')
->andReturn('Test Page');
$model->title = 'Test Page'; // I also tried this
$result = $this->doSomething($model);
$this->assertEquals('/test-page', $result);
}
public function doSomething($model): string
{
print_r([$model->title, $model->title ?? 'default']);
...
...
}
Output:
Array
(
[0] => Test Page
[1] => default
}
When I use $model->title directly, it works fine and returns the mocked value ('Test Page'). However, when I try to use $model->title ?? 'default', the fallback ('default') is always returned, as if the title property doesn't exist or is null.
Is there a way to make the null coalescing operator (??) work reliably with Mockery mocks in PHP?
Stack: PHP 8.2, PHPUnit 10.5 with Laravel 11.33.2
Note: I'm not trying to test the model itself or any part of Laravel's framework. My goal is simply to make the model return a specific value in a practical way without setting up factories its relations.