phpunit - mockbuilder - set mock object internal property

后端 未结 5 953
别那么骄傲
别那么骄傲 2020-12-24 00:55

Is it possible to create a mock object with disabled constructor and manually setted protected properties?

Here is an idiotic example:

class A {
             


        
5条回答
  •  忘掉有多难
    2020-12-24 01:32

    Based on @rsahai91 answer above, created a new helper for making multiple methods accessible. Can be private or protected

    /**
     * Makes any properties (private/protected etc) accessible on a given object via reflection
     *
     * @param $object - instance in which properties are being modified
     * @param array $properties - associative array ['propertyName' => 'propertyValue']
     * @return void
     * @throws ReflectionException
     */
    public function setProperties($object, $properties)
    {
        $reflection = new ReflectionClass($object);
        foreach ($properties as $name => $value) {
            $reflection_property = $reflection->getProperty($name);
            $reflection_property->setAccessible(true);
            $reflection_property->setValue($object, $value);
        }
    }
    

    Example use:

    $mock = $this->createMock(MyClass::class);
    
    $this->setProperties($mock, [
        'propname1' => 'valueOfPrivateProp1',
        'propname2' => 'valueOfPrivateProp2'
    ]);
    

提交回复
热议问题