Dart unit testing with throwsA

336
import 'package:test/test.dart';
import 'dart:io';

void main() {
  Future<bool> testFunction() async {
    try {
      throw SocketException('bad error message');
    } on SocketException catch (_) {
      throw Exception('My custom message');
    }
  }

  test('test function', () async {
    expect(
      () async => await testFunction(),
      throwsA(
        (e) => e is Exception,
      ),
    );
  });
}

Launching test/test_1.dart on Android SDK built for x86 in debug mode...

Connecting to VM Service at ws://127.0.0.1:43155/59iZNP08VJI=/ws
I/flutter ( 5523): 00:00 +0: test function
I/flutter ( 5523): 00:00 +1: All tests passed!
Share:
336
Larva Pox
Author by

Larva Pox

Updated on December 26, 2022

Comments

  • Larva Pox
    Larva Pox over 1 year

    I am having some trouble when unit testing using expect(method, throwsA)

    So I have a Future function that is doing some tasks and is catching a SocketEXception when it pops, then throws an Exception with a better message.

    Here's a sample code that you can use that triggers my problem when testing it:

      Future<void> testFunction() async{
        try{
          throw SocketException("bad error message");
        } on SocketException catch (_) {
          throw Exception("My custom message");
        }
      }
    
      test('test function', () async {
        expect(
            testFunction(),
            throwsA(Exception(
                "My custom message")));
      });
    

    and here's the output of the test:

    Expected: throws _Exception:<Exception: My custom message>
    Actual: <Instance of 'Future<void>'>
    Which: threw _Exception:<Exception: My custom message>
    

    I don't know why the test isn't working as it expects a throw, and the actual is throwing the exact same error, I might be doing something wrong as I'm a beginner, if someone can help me understand why it isn't working, it would be cool.

    Thanks.