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

Issue

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');
  });
}

Solution

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

Answered By – Gpack

Answer Checked By – Marilyn (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.