Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the timeout of test in dart's unittest?

Is it possible to set the max time that a test can run? Just like:

@Test(timeout=1000)
public void testSomething() {}

in jUnit?

like image 478
Freewind Avatar asked Jan 31 '14 13:01

Freewind


2 Answers

Yes, you can put this line of code above your import statements now to determine your test timeout time.

@Timeout(const Duration(seconds: 45))

https://pub.dartlang.org/packages/test#timeouts

like image 89
atreeon Avatar answered Sep 26 '22 20:09

atreeon


Try to add the following line in the main() of you tests

void main(List<String> args) {
  useHtmlEnhancedConfiguration(); // (or some other configuration setting)
  unittestConfiguration.timeout = new Duration(seconds: 3); // <<== add this line

  test(() {
    // do some tests
  });
}

You could easily setup a time guard using setUp() and tearDown() and a Timer

library x;

import 'dart:async';
import 'package:unittest/unittest.dart';

void main(List<String> args) {
  group("some group", () {
    Timer timeout;
    setUp(() {
      // fail the test after Duration
      timeout = new Timer(new Duration(seconds: 1), () => fail("timed out"));
    });

    tearDown(() {
        // if the test already ended, cancel the timeout
        timeout.cancel();
    });

    test("some very slow test", () {
      var callback = expectAsync0((){});
      new Timer(new Duration(milliseconds: 1500), () {
        expect(true, equals(true));
        callback();
      });
    });

    test("another very slow test", () {
      var callback = expectAsync0((){});
      new Timer(new Duration(milliseconds: 1500), () {
        expect(true, equals(true));
        callback();
      });
    });


    test("a fast test", () {
      var callback = expectAsync0((){});
      new Timer(new Duration(milliseconds: 500), () {
        expect(true, equals(true));
        callback();
      });
    });

  });
}

this fails the entire group, but groups can be nested, therefore you have full control what tests should be watched for timeouts.

like image 43
Günter Zöchbauer Avatar answered Sep 25 '22 20:09

Günter Zöchbauer