> Using Future.delayed(Duration()) we can wait for specific duration.

Example 1 :

We create a custom class in which we implement timer features.

import 'dart:async';
class CustomTimer {
 int _seconds;
 bool _isRunning = false;
 Timer? _timer;
 CustomTimer(this._seconds);
 int get seconds => _seconds;
 void start() {
   _isRunning = true;
   _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
     if (_seconds > 0) {
       _seconds--;
     } else {
       _timer?.cancel();
       _isRunning = false;
     }
   });
 }
}

Now we add unit test related code and use this CustomTimer class inside unit test file.

import 'dart:async';
import 'package:flutter_test/flutter_test.dart';
import '../test_class/custom_timer.dart';

void main() {
 group('Timer Tests', () {
   test("Testing timer", () async {
     CustomTimer timer = CustomTimer(10); // Start with 10 seconds
     int startTime = timer.seconds;
     timer.start();
     // Wait for 2 seconds
     await Future.delayed(const Duration(seconds: 2));
     // Check if the timer's seconds are within an expected range
     expect(timer.seconds, inInclusiveRange(startTime - 2, startTime - 1));
   });
 });
}

In above example, we can expect seconds is inInclusiveRange(startTime – 2 , startTime – 1) after delaying 2 seconds.

Output

admin@Mac-mini-3 testing % flutter test
00:01 +1:
All tests passed!

Support On Demand!

Flutter