How do I test function with compute() in Flutter?

934 views Asked by At

I am trying to test async method with compute() function, but when I run test('Compute test') via Android Studio, it doesn't finish and print only 'Start test'.

The test was run using the command:

../bin/flutter --no-color test --machine --start-paused --plain-name "Compute test" test/test_compute.dart

Test class:

import 'package:flutter/foundation.dart';
import 'package:flutter_test/flutter_test.dart';

int testCompute(int value) {
  print('Test compute');
  return value + 1;
}

void main() {
  test('Compute test', () async {
    print('Start test');
    int result = await compute(testCompute, 0);
    print('End test: $result');
  });
}
2

There are 2 answers

0
Gpack On BEST ANSWER

Someone from Google said you need to run your test with runAsync().

void main() {
  testWidgets('compute', (WidgetTester tester) async {
    dynamic data = await tester.runAsync(() => parseData('[1]'));
    print(data);
  });
}

Future<dynamic> parseData(String str) => compute(parseJson, str);

dynamic parseJson(String str) {
  return json.decode(str);
}

Source: https://github.com/flutter/flutter/issues/35484#issuecomment-517931625

0
acbelter On

To work correctly, the test should be run without --start_paused argument.