У меня есть как вопрос «как это сделать», так и «как это делается».
Class realClass {
private $privateProperty;
public function __construct($someArray, $someString) {
// stuff
}
public function setProperty($someArray) {
$this->privateProperty = $someArray;
}
}
class testRealClass extends TestCase {
// creating a mock because don't want to have tests depending on arguments passed to the constructor
public function setUp(): void
{
$this->classToTest = $this->getMockBuilder(realClass::class)
->disableOriginalConstructor()
->setMethods(null)
->getMock();
}
// testing the set of the variable. In order to know if it was set, without using a getter,
// we probably need to use reflection
public function testSetPrivateProperty() {
$this->classToTest->setProperty([1,2,3]);
// This will not work as the property is private
// echo $this->classToTest->privateProperty;
// Reflecting the mock, makes sense? How does this work?
$reflect = new \ReflectionClass($this->classToTest);
$property = $reflect->getProperty('privateProperty');
$property->setAccessible(true);
var_dump($property->getValue($this->classToTest));
}
}
При выполнении этого я получаю исключение ReflectionException: свойство privateProperty не существует.
Если я сделаю print_r из отражений-> getProperties, я смогу увидеть свойство там.
Я понимаю, что это было бы легко достижимо с помощью всего лишь получателя в realClass, но примите это как упражнение.
Это вообще имеет смысл, или это не сработает, потому что это просто неправильно?
Спасибо всем
(здесь написал код, так что если я пропускаю ";", "(", et c, игнорируйте его:)