问题
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