Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
578 views
in Technique[技术] by (71.8m points)

flutter - 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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!

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...