Unit Testing Magic Methods

浪子不回头ぞ 提交于 2020-01-14 09:48:54

问题


When it comes to unit-testing implementations of magic methods in PHP, what is the recommended means of invoking those methods?

I see three options available:

  • Invoking them explicitly/directly:

    $object->__get('someValue');

  • Invoking them indirectly (using whatever action is intended to trigger them):

    $object->someValue; \\ Where __get() is implemented.

  • Invoking them using both methods.

Are there any unit testing veterans that could explain which (if any) would be the obvious choice, and why that might be?

(This may be dancing close to subjective/debate territory, but I will ask in the hopes that there are some generally accepted principles I should consider when approaching this question.)


回答1:


You should be testing observable behavior. So, the second one ($obj->property) must be tested, no question.

As for actually calling the getter directly, that's more of a judgement call. Once you have said __get('someProperty'), in my opinion you've pretty much set in stone that it is a magic property. Since I try to never change the tests, that complicates things quite a bit if, for some reason, I want that to be a plain old non-magic property. On the plus side, you can call the getter and get the property the other way as well and ensure they both have the exact same result.



来源:https://stackoverflow.com/questions/13148669/unit-testing-magic-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!