PHPUnit Mock an object's properties
When you encounter a dependency injection scenario where a class relies on a property of another object, unit testing often hits a wall. You can easily mock the methods of that dependency using getMockBuilder(), but accessing or populating private properties directly feels impossible with standard mocking tools. This is a common stumbling block when trying to isolate specific state changes in your test suite.
The core issue here isn't that PHPUnit lacks the capability, but rather that the default mock generation strategy focuses on method behavior, not property mutation. By default, PHPUnit\Framework\MockObject\MockBuilder creates a partial mock where properties are either null or inaccessible from the outside unless explicitly defined as public within the mock itself. If your production code sets a private property like $this->_object, and you try to access its properties via the mock without configuring them, PHPUnit will throw an exception because the property doesn't exist on the mock instance in a writable state.
To resolve this, you need to configure the mock's properties before returning the instance from your test method. The getMock() method returns a MockObject which supports the setMethodVisibility() and direct property setting via __get or __set magic methods, but there is a more direct approach for properties that should be writable by the class under test.
Consider this specific scenario: you have MyClass that accepts an object and stores it in a private field _object. Your goal is to mock $object so that when methodUnderTest returns $this->_object->property, your test can control what value is returned.
Here is how you configure the mock to allow property assignment:
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
class MyClassTest extends TestCase
{
public function testMethodUnderTestReturnsProperty()
{
// Create the mock for the dependency
$mockObject = $this->createMock('YourNamespace\Object');
// The trick is to make the property writable if it's not already accessible
// However, simply creating a mock often leaves properties as 'not set'.
// To simulate an object with specific properties, we use __get/__set logic
// or define the property explicitly in the mock.
// Define the property on the mock so it acts like a real object's property
$mockObject->expects($this->any())
->method('__get')
->with('property')
->willReturn('expected_value');
// If you need to set properties dynamically in the test:
$reflection = new ReflectionClass($mockObject);
$property = $reflection->getProperty('property');
$property->setAccessible(true);
$property->setValue($mockObject, 'custom_data');
$myClass = new MyClass();
$result = $myClass->methodUnderTest($mockObject);
$this->assertEquals('expected_value', $result);
}
}
However, there is a more idiomatic way to handle this without relying on reflection magic every time. If the property you are mocking is private in your real object, you can't directly "set" it on a standard mock unless you define it as a public property in the mock builder or use willReturnOnConsecutiveCalls for methods that trigger getter logic.
A cleaner approach often involves using ->willReturn() on the getter method if the dependency follows standard accessor patterns. If the dependency exposes properties via getters (e.g., getProperty()), you can simply chain expectations:
$mockObject = $this->createMock('YourNamespace\Object');
$mockObject->method('getProperty')->willReturn('test_value');
But if you are dealing with a private property accessed directly ($this->_object->property), the mock must expose that property. The most robust solution when direct property access is required is to manually define the property on the mock instance or use getMock() with explicit properties defined in the constructor or via setMethods.
If you are working within a Laravel application, this pattern of mocking private dependencies is particularly relevant when testing service classes that manage state. You might find useful patterns and community discussions regarding this specific edge case at https://laravelcompany.com, where developers often share snippets for handling complex mock configurations in the Laravel ecosystem.
The trade-off here is verbosity versus control. Using reflection to set property values on a mock bypasses visibility modifiers, effectively treating the mock as if it were public. While this works perfectly for unit tests where isolation is key, it means your test mocks will behave differently than production code regarding access levels. This is acceptable in unit testing but something to keep in mind if you ever migrate these mocks to integration tests or use them with tools that enforce strict visibility rules.
Ultimately, the ability to manipulate property values on a mock comes down to understanding how PHPUnit\Framework\MockObject generates its internal structure. By leveraging reflection or defining getter methods explicitly, you gain full control over the state of your mocked dependencies, ensuring your unit tests accurately reflect the logic you intend to verify.