How can I “sleep” a Dart program

前端 未结 7 2227
梦谈多话
梦谈多话 2020-12-12 23:39

I like to simulate an asynchronous web service call in my Dart application for testing. To simulate the randomness of these mock calls responding (possibly out of order) I\

7条回答
  •  抹茶落季
    2020-12-12 23:57

    I also needed to wait for a service to complete during a unit test. I implemented this way:

    void main()
    {
        test('Send packages using isolate', () async {
            await SendingService().execute();
        });
        // Loop to the amount of time the service will take to complete
        for( int seconds = 0; seconds < 10; seconds++ ) {
            test('Waiting 1 second...', () {
                sleep(const Duration(seconds:1));
            } );
        }
    }
    ...
    class SendingService {
        Isolate _isolate;
        Future execute() async {
            ...
            final MyMessage msg = new MyMessage(...);
            ...
            Isolate.spawn(_send, msg)
                .then((Isolate isolate) => _isolate = isolate);
        }
        static void _send(MyMessage msg) {
            final IMyApi api = new IMyApi();
            api.send(msg.data)
                .then((ignored) {
                    ...
                })
                .catchError((e) {
                    ...
                } );
        }
    }
    

提交回复
热议问题