phpunit - mockbuilder - set mock object internal property

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

    It would be amazing if every codebase used DI and IoC, and never did stuff like this:

    public function __construct(BlahClass $blah)
    {
        $this->protectedProperty = new FooClass($blah);
    }
    

    You can use a mock BlahClass in the constructor, sure, but then the constructor sets a protected property to something you CAN'T mock.

    So you're probably thinking "Well refactor the constructor to take a FooClass instead of a BlahClass, then you don't have to instantiate the FooClass in the constructor, and you can put in a mock instead!" Well, you'd be right, if that didn't mean you would have to change every usage of the class in the entire codebase to give it a FooClass instead of a BlahClass.

    Not every codebase is perfect, and sometimes you just need to get stuff done. And that means, yes, sometimes you need to break the "only test public APIs" rule.

提交回复
热议问题