phpunit - mockbuilder - set mock object internal property

后端 未结 5 935
别那么骄傲
别那么骄傲 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:54

    Based on the accepted answer from @gontrollez, since we are using a mock builder we do not have the need to call new A; since we can use the class name instead.

        $a = $this->getMockBuilder(A::class)
            ->disableOriginalConstructor()
            ->getMock();
    
        $reflection = new ReflectionClass(A::class);
        $reflection_property = $reflection->getProperty('p');
        $reflection_property->setAccessible(true);
    
        $reflection_property->setValue($a, 2);
    

提交回复
热议问题