Note that there are some explanatory texts on larger screens.

plurals
  1. POCan I "Mock" time in PHPUnit?
    text
    copied!<p>... not knowing if 'mock' is the right word.</p> <p>Anyway, I have an inherited code-base that I'm trying to write some tests for that are time-based. Trying not to be <em>too</em> vague, the code is related to looking at the history of an item and determining if that item has now based a time threshold.</p> <p>At some point I also need to test adding something to that history and checking that the threshold is now changed (and, obviously, correct).</p> <p>The problem that I'm hitting is that part of the code I'm testing is using calls to time() and so I'm finding it really hard to know exactly what the threshold time should be, based on the fact that I'm not quite sure exactly when that time() function is going to be called.</p> <p>So my question is basically this: is there some way for me to 'override' the time() call, or somehow 'mock out' the time, such that my tests are working in a 'known time'?</p> <p>Or do I just have to accept the fact that I'm going to have to do something in the code that I'm testing, to somehow allow me to force it to use a particular time if need be? </p> <p>Either way, are there any 'common practices' for developing time-sensitive functionality that is test friendly?</p> <p>Edit: Part of my problem, too, is the fact that the time that things occurred in history affect the threshold. Here's an example of part of my problem...</p> <p>Imagine you have a banana and you're trying to work out when it needs to be eaten by. Let's say that it will expire within 3 days, unless it was sprayed with some chemical, in which case we add 4 days to the expiry, <em>from the time the spray was applied</em>. Then, we can add another 3 months to it by freezing it, but if it's been frozen then we only have 1 day to use it after it thaws.</p> <p>All of these rules are dictated by historical timings. I agree that I could use the Dominik's suggestion of testing within a few seconds, but what of my historical data? Should I just 'create' that on the fly?</p> <p>As you may or may not be able to tell, I'm still trying to get a hang of all of this 'testing' concept ;)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload