Dieser Artikel ist nur auf Englisch erschienen.
12 Replies to “PHP: “Mocking” built-in functions like time() in Unit Tests”
Comments are closed.
Dipl. Inform. Fabian Schmengler | Magento Certified Developer | Magento Certified Solution Specialist
Dieser Artikel ist nur auf Englisch erschienen.
Comments are closed.
This looks excellent. The cleanest way to mock time that I have seen so far !
Thanks a lot for the tip 🙂
I liked this strategy so much… I pushed it a little further down the line 🙂
In this post in programmers stackexchange I was searching for a way to organize my tests.
I finally implemented a solution following the steps you describe in this page, overriding the DateTime() function. Available here for the curious 🙂
Thanks again !
I recently implemented the library php-mock which uses that language feature for mocking non deterministic PHP functions like time().
Very nice library, good job! Definitely going to use that when I need it the next time!
In time() function better return ?: \time(); otherwise it will just call itself
Thanks for noticing! I updated the code.
I’ve just refactored this method for my CakePHP 3 app in it works a treat. Thank you so much!
“Important Implication: It does not work if you use the global functions with fully qualified names (i.E. \time()) in your test subjects!”
So, any ideas on how to test when the fully qualified name is used?
With the runkit extension, you can redefine PHP functions. I don’t know any better method, except refactoring the code under test. See also: http://stackoverflow.com/questions/2371854/can-i-mock-time-in-phpunit
Huge help! Made it easy to essentially “disable” the mail() function in our Email class by simply returning true when the mail() function is called.
The problem with this approach is it requires you to make assumptions about the internal workings of a given class, meaning that if you change how a class actually works then your unit tests might break even though the class itself is still fine.