Geek Culture
Published in

Geek Culture

Unit testing DateTime.now() with the help of Dart extensions

The Problem…

A Solution…

extension ExtendedDateTime on DateTime { static DateTime? _customTime; static DateTime get current { return _customTime ?? DateTime.now(); } static set customTime(DateTime customTime) { _customTime = customTime; } }
class User { final String userName; final DateTime createdDate; User(this.userName, this.createdDate); static User createUser(String userName) => User(userName, DateTime.now()); }
final result = User.createUser('Reme'); expect(result, equals(User('Reme', DateTime.now());
class User { final String userName; final DateTime createdDate; User(this.userName, this.createdDate); static User createUser(String userName) => User(userName, ExtendedDateTime.current); }
ExtendedDateTime.current = DateTime.parse( "2020-05-15 13:07:53.531Z", ); final result = User.createUser('Reme'); expect(result, equals(User('Reme', "2020-05-15 13:07:53.531Z");

Final thoughts…

A new tech publication by Start it up (https://medium.com/swlh).