Flutter:测试是否抛出特定异常

Flutter: Test that a specific exception is thrown

简而言之,在 dart 中进行单元测试时,throwsA(anything) 对我来说不够。如何测试 特定的错误消息或类型 ?

这是我想捕获的错误:

class MyCustErr implements Exception {
  String term;

  String errMsg() => 'You have already added a container with the id 
  $term. Duplicates are not allowed';

  MyCustErr({this.term});
}

这是当前通过的断言,但想检查上面的错误类型:

expect(() => operations.lookupOrderDetails(), throwsA(anything));

这就是我想要做的:

expect(() => operations.lookupOrderDetails(), throwsA(MyCustErr));

这应该可以满足您的要求:

expect(() => operations.lookupOrderDetails(), throwsA(isA<MyCustErr>()));

如果你只是想检查异常检查这个answer:

万一有人想像我一样使用异步函数进行测试,你需要做的就是在 expect 中添加 async 关键字,记住 lookupOrderDetails 是一个异步函数功能:

expect(() **async** => **await** operations.lookupOrderDetails(), throwsA(const TypeMatcher<MyCustErr>()));

expect(() **async** => **await** operations.lookupOrderDetails(), isInstanceOf<MyCustErr>()));

还是用了Gunter的回答,很好!

首先导入正确的包'package:matcher/matcher.dart';

expect(() => yourOperation.yourMethod(),
      throwsA(const TypeMatcher<YourException>()));

在 Flutter 1.12.1 中弃用了“TypeMatcher<>”后,我发现它可以工作:

expect(() => operations.lookupOrderDetails(), throwsA(isInstanceOf<MyCustErr>()));

当前期望函数调用抛出异常的正确方法是:

expect(operations.lookupOrderDetails, throwsA(isA<MyCustErr>()));`

截至 2021 年 4 月,这是正确的方法。

正确的方法

import 'package:dcli/dcli.dart';
import 'package:test/test.dart';

 /// GOOD: works in all circumstances.
 expect(() => restoreFile(file), throwsA(isA<RestoreFileException>()));

一些示例显示:

方法不正确

import 'package:dcli/dcli.dart';
import 'package:test/test.dart';
 /// BAD: works but not in all circumstances
 expect(restoreFile(file), throwsA(isA<RestoreFileException>()));

注意 expect 后面缺少的“() =>”。

区别在于第一种方法适用于 return 无效的函数,而第二种方法则无效。

所以第一种方法应该是首选技术。

测试特定错误消息:

同时检查异常内容

import 'package:dcli/dcli.dart';
import 'package:test/test.dart';

    expect(
        () => copy(from, to),
        throwsA(predicate((e) =>
            e is CopyException &&
            e.message == 'The from file ${truepath(from)} does not exists.')));