Freewind
Freewind

Reputation: 198358

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?

Upvotes: 10

Views: 4905

Answers (2)

atreeon
atreeon

Reputation: 24167

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

Upvotes: 10

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657937

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.

Upvotes: 4

Related Questions