简体   繁体   中英

Dart unit testing with throwsA

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.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM