Skip to content

Better support for test cases: Overriding the current time #105

@peteringraham

Description

@peteringraham

Apologies if there's already a good solution for this out there. This is more a feature request than a bug.

In a test, it's nice to force certain dates to be returned. Sure, you can do something like add an "overrideTime" variable, set it in tests, then do this every time you'd check the time:

let current_time : i64 ;
if !overrideTime {
current_time = UTC::now().timestamp();
} else {
current_time = forced_timestamp;
}

But meh. It'd be nicer if instead there was a function similar to, say, JODA setCurrentMillisFixed :
http://joda-time.sourceforge.net/api-release/org/joda/time/DateTimeUtils.html#setCurrentMillisFixed(long)

So then you'd have something like:

[test]

fn test_that_requires_a_specific_time() {
// This time is 2017-02-28T10:00Z
UTC::setFixed(1488276000);
// UTC::now() will now lie and always return the above value.
...
}

And then include a setCurrentMillisSystem() that undoes the above, for all that it'd be rarely called.

Alternatively: create a provider class, and then have it understood that classes should only ever ask the provider for the time rather than making raw now() calls. e.g. Clock has a getTime() call, and it's implemented by SystemClock & FakeClock. System Clock calls now() like normal, but if you pass in a FakeClock in a test, then that FakeClock can do whatever craziness you want. This is a bit more powerful since now people can write FakeClocks that, say, actually run forward but from a set date or the like.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions