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

Issue

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

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

in jUnit?

Solution

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.

Answered By – Günter Zöchbauer

Answer Checked By – Cary Denson (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.