我找到了一个适用于普通对象的解决方案,但似乎不适用于模拟对象。
下面的测试失败,并显示以下消息:无法设置 Mock_ClassToTest_40ea0b83 对象类型的 someProperty 属性:属性 someProperty 不存在
。
class sampleTestClass extends PHPUnit_Framework_TestCase
{
function test() {
$object = $this->getMockForAbstractClass(ClassToTest::class, [], '', false);
$this->setProtectedProperty($object, 'someProperty', 'value');
}
private function getReflectionProperty($object, $property) {
$reflection = new ReflectionClass($object);
$reflectionProperty = $reflection->getProperty($property);
$reflectionProperty->setAccessible(true);
return $reflectionProperty;
}
/**
* This method modifies the protected properties of any object.
* @param object $object The object to modify.
* @param string $property The name of the property to modify.
* @param mixed $value The value to set.
* @throws TestingException
*/
function setProtectedProperty(&$object, $property, $value) {
try {
$reflectionProperty = $this->getReflectionProperty($object, $property);
$reflectionProperty->setValue($object, $value);
}
catch ( Exception $e ) {
throw new TestingException("Unable to set property {$property} of object type " . get_class($object) .
': ' . $e->getMessage(), 0, $e);
}
}
}
abstract class ClassToTest
{
private $someProperty;
abstract function someFunc();
}
class TestingException extends Exception
{
}
编辑:2016年8月31日下午4:32 EST 根据Katie的回答更新了代码。