【问题标题】:Dart unit testing with throwsA使用 throwsA 进行 Dart 单元测试
【发布时间】:2025-12-28 05:15:13
【问题描述】:

我在使用 expect(method, throwsA) 进行单元测试时遇到了一些麻烦

所以我有一个 Future 函数,它正在执行一些任务并在它弹出时捕获一个 SocketEXception,然后抛出一个带有更好消息的异常。

这是一个示例代码,您可以使用它在测试时触发我的问题:

  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")));
  });

这是测试的输出:

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

我不知道为什么测试无法正常工作,因为它期望抛出,而实际抛出完全相同的错误,我可能做错了,因为我是初学者,如果有人可以帮助我理解为什么它不起作用,那会很酷。

谢谢。

【问题讨论】:

    标签: unit-testing flutter dart exception


    【解决方案1】:
    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,
          ),
        );
      });
    }
    

    在调试模式下在为 x86 构建的 Android SDK 上启动 test/test_1.dart...

    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!
    

    【讨论】: