phpunit - mockbuilder - set mock object internal property

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

    You can make the property public by using Reflection, and then set the desired value:

    $a = new A;
    $reflection = new ReflectionClass($a);
    $reflection_property = $reflection->getProperty('p');
    $reflection_property->setAccessible(true);
    
    $reflection_property->setValue($a, 2);
    

    Anyway in your example you don't need to set p value for the Exception to be raised. You are using a mock for being able to take control over the object behaviour, without taking into account it's internals.

    So, instead of setting p = 2 so an Exception is raised, you configure the mock to raise an Exception when the blah method is called:

    $mockA = $this->getMockBuilder('A')
            ->disableOriginalConstructor()
            ->getMock();
    $mockA->expects($this->any())
             ->method('blah')
             ->will($this->throwException(new Exception));
    

    Last, it's strange that you're mocking the A class in the ATest. You usually mock the dependencies needed by the object you're testing.

    Hope this helps.

提交回复
热议问题