Time is an integral part of our lives — the same for the applications we develop. From the software engineering perspective, time is just another dependency which we introduce to our systems. And that’s OK. The situation might start to be problematic when some parts of the system are more dependent on time. How to test this component? How to mock the time?
In this article, I’m going to show you our approach to develop and test components which depend on time. We’ll get rid of time-dependency by creating a proper abstraction and applying the dependency inversion principle. Ultimately, we’ll create a mechanism to mock time in tests. Ready?
The larger a project, the harder it is to test the code, and with most of the tests being functional – we have to face the problem: we finalize the task, the user story, or close the entire sprint and we have to wait for the tests for hours. This process can be vastly accelerated, even in legacy applications from the era of the PHP 4.
Above all, it is worth introducing unit tests into the new code – extract dependencies outside the code and test what is actually being developed. The tests are supposed to check our logical code, not the library or ORM. The introduction of unit tests is, however, a long-term step that does not give immediate results, which is why I’d like to show you what can be done on top of that.
Firstly, it must be said that one could write a book about the subject and still barely scratch the surface, so I’ll keep this article very brief and only touch upon the practical aspects based on my own experience – assuming a more difficult scenario, when the project has a lot of tests using the MySQL database.