0

The unit test I write below doesn't work when there are 3 expect, how can I rewrite the unit test below:

test('400 bad response', () async {
  when(
    () => sampleClient.getTransaction(
        '1'),
  ).thenThrow(DioError(
      response: Response(
          statusCode: 400,
          data: badRepsonseJson,
          requestOptions: RequestOptions(path: '')),
      requestOptions: RequestOptions(path: '')));
  final call = sampleService.getTransactionByHash(
      '1');

  expect(() => call, throwsA(TypeMatcher<SampleException>())); // Expect 1
  try {
    await sampleService.getTransactionByHash(
        '1');
  } on SampleException catch (e) {
    expect(e.errorCode, badResponse.statusCode); // Expect 2
    expect(e.message, badResponse.message); // Expect 3
  }
});
Alvin
  • 8,219
  • 25
  • 96
  • 177
  • Exactly what do you mean by "doesn't work"? What happens? Can you provide a minimal, reproducible example? – jamesdlin Sep 04 '22 at 15:26

1 Answers1

0
final call = sampleService.getTransactionByHash(
    '1');

expect(() => call, throwsA(TypeMatcher<SampleException>())); // Expect 1

I would not expect that expect to succeed. Invoking () => call just returns the already computed value of the call variable, which cannot fail.

If you instead expect sampleService.getTransactionByHash('1'); to throw an exception, then you need to invoke that in your callback to expect:

expect(
  () => sampleService.getTransactionByHash('1'),
  throwsA(TypeMatcher<SampleException>()),
);
Alvin
  • 8,219
  • 25
  • 96
  • 177
jamesdlin
  • 81,374
  • 13
  • 159
  • 204
  • 1
    Alternatively, `call` is a `Future`, because `getTransactionByHash` is async, in which case you should just do `expect(call, throwsA(...));`. – lrn Sep 05 '22 at 15:12