我環顧四周,發現了一個適用於普通對象的解決方案,但它似乎不適用於嘲笑。如何爲抽象類設置mock的受保護屬性?
以下測試失敗,消息:Unable to set property someProperty of object type Mock_ClassToTest_40ea0b83: Property someProperty does not exist
。
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 響應answer by Katie更新後的代碼。
你爲什麼要測試一個抽象類? – dm03514
這樣我就不必爲擴展它們的類編寫額外的測試用例。 – Person93
您仍然必須爲擴展抽象類的類編寫測試用例。它們實現基類的抽象函數,並且沒有辦法通過測試基類來測試這些函數。 – axiac