Merge custom constructor into default using optional params
diff --git a/lib/clock.dart b/lib/clock.dart
index a9fbd2a..66f6b39 100644
--- a/lib/clock.dart
+++ b/lib/clock.dart
@@ -17,6 +17,11 @@
/// Returns current time.
typedef DateTime TimeFunction();
+DateTime _systemTime() => new DateTime.now();
+
+/// A predefined instance of [Clock] that's based on system clock.
+const SYSTEM_CLOCK = const Clock();
+
/// Provides points in time relative to the current point in time, for example:
/// now, 2 days ago, 4 weeks from now, etc.
///
@@ -29,13 +34,14 @@
final TimeFunction _time;
- /// Creates [Clock] based on the system clock.
- Clock() : _time = (() => new DateTime.now());
-
- /// Creates [Clock] based on user-defined [TimeFunction]. For example, in
- /// unit-tests you might want to control what time it is now and set date and
- /// time expectations.
- Clock.custom(this._time);
+ /// Creates a clock based on the given [timeFunc].
+ ///
+ /// If [timeFunc] is not provided, creates [Clock] based on system clock.
+ ///
+ /// Custom [timeFunc] can be useful in unit-tests. For example, you might
+ /// want to control what time it is now and set date and time expectations in
+ /// your test cases.
+ const Clock([TimeFunction timeFunc = _systemTime]) : _time = timeFunc;
/// Creates [Clock] that returns fixed [time] value. Useful in unit-tests.
Clock.fixed(DateTime time) : _time = (() => time);
diff --git a/test/clock_test.dart b/test/clock_test.dart
index 0c7651f..a9e3bc6 100644
--- a/test/clock_test.dart
+++ b/test/clock_test.dart
@@ -23,20 +23,25 @@
test("should return a non-null value from system clock", () {
expect(new Clock().now(), isNotNull);
+ expect(SYSTEM_CLOCK.now(), isNotNull);
});
// This test may be flaky on certain systems. I ran it over 10 million
// cycles on my machine without any failures, but that's no guarantee.
test("should be close enough to system clock", () {
- var testValue = new Clock().now();
- var now = new DateTime.now();
// I picked 2ms because 1ms was starting to get flaky.
- expect(now.difference(testValue).inMilliseconds.abs(), lessThan(2));
+ var epsilon = 2;
+ expect(new DateTime.now().difference(
+ new Clock().now()).inMilliseconds.abs(),
+ lessThan(epsilon));
+ expect(new DateTime.now().difference(
+ SYSTEM_CLOCK.now()).inMilliseconds.abs(),
+ lessThan(epsilon));
});
test("should return time provided by custom TimeFunction", () {
var time = new DateTime(2013);
- var fixedClock = new Clock.custom(() => time);
+ var fixedClock = new Clock(() => time);
expect(fixedClock.now(), new DateTime(2013));
time = new DateTime(2014);