News Feed
Sections




News Archive
Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

Fabian Schmengler's Blog:
"Mocking" built-in functions like time() in Unit
March 18, 2011 @ 08:52:03

In a recent post to his blog Fabian Schmengler looks at mocking something in your unit tests that could cause problems in certain situations - needing a specific kind of response from a built-in PHP function. In his case, he shows how to mock time to return the same formatted date.

A common problem in Unit Testing in PHP is testing something that depends on the current time. For a determined test it should be possible to set the time in your test script without really changing the system settings. In this article I'll describe how it is usually done with OOP and then come to an alternative solution with much less code that makes use of the new features in PHP 5.3.

He shows a usual approach using dependency injection and a class wrapper to handle the set and fetch of the date value. His alternative uses namespacing to redefine the internal PHP function into something custom. Then, when the test is executed, it can use that custom namespace's version, overriding the default. It's a pretty seamless option and can save you a good bit of time and hassle with other classes each time you need to customize the results.

0 comments voice your opinion now!
mock phpunit unittest time namespace


blog comments powered by Disqus

Similar Posts

Sebastian Bergmann's Blog: PHPUnit as a Project Mess Detector

PHPMaster.com: An Introduction to Mock Object Testing

Sebastian Bergmann's Blog: Isolated (and Parallel) Test Execution

UncleCode.com: Install PHPUnit Manually without Pear for a Single Project

Matthias Noback: A better PHP testing experience Part I: Moving away from assertion-centric testing


Community Events

Don't see your event here?
Let us know!


community introduction extension wordpress unittest framework laravel5 release language podcast opinion library api interview voicesoftheelephpant threedevsandamaybe series feature development laravel

All content copyright, 2015 PHPDeveloper.org :: info@phpdeveloper.org - Powered by the Solar PHP Framework