Skip to content

Testing with Future.error #23

@shripal17

Description

@shripal17

I am trying to test my async function which accepts a Future and also returns a Future.
If the input Future throws an error, I handle it and return a -1 instead.

e.g.

Main Code

class Processor {
  Future<int> execute(Future<int> process) async {
    try {
      final result = await process;
      return result;
    } catch (e) {
      return -1;
    }
  }
}

Test

void main() {
  final processor = Processor();
  final process = Future.value(1);

  getErroneousProcess() => Future<int>.error(SignalException("something went wrong"));

  test('exception', () async {
    final result = await processor.execute(getErroneousProcess());
    expect(result, -1);
  });

  test('success', () async {
    final result = await processor.execute(process);
    expect(result, 1);
  });
}

Parameterized version

void main() {
  final processor = Processor();
  final process = Future.value(1);

  getErroneousProcess() => Future<int>.error(SignalException("something went wrong"));

  parameterizedTest(
    'process',
    [
      [getErroneousProcess(), -1],
      [process, 1],
    ],
    (process, expected) async {
      final result = await processor.execute(process);
      expect(result, expected);
    },
  );
}

Problem

Expectation

The parameterized version runs and tests code the same way as non-parameterized version.

Reality

The parameterized test fails with output did not complete [E]

$ flutter test

00:00 +0 -1: loading my_project/test/test_error.dart [E]                                                                                                                                                                                                               
  Failed to load "my_project/test/test_error.dart": something went wrong
  
00:00 +0 -1: process [ Instance of 'Future<int>', -1 ] - did not complete [E]                                                                                                                                                                                                                        
00:00 +0 -1: process [ Instance of 'Future<int>', 1 ] - did not complete [E]                                                                                                                                                                                                                         
00:00 +0 -1: Some tests failed.                

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions