26

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

这是我想捕捉的错误:

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

4

6 回答 6

45

这应该做你想要的:

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

如果您只想检查异常,请检查此答案

于 2019-01-17T17:41:12.263 回答
15

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

expect(() => operations.lookupOrderDetails(), throwsA(isInstanceOf<MyCustErr>()));
于 2020-01-27T10:48:41.827 回答
13

截至 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>()));

注意期望之后缺少的 '() => '。

不同之处在于第一种方法适用于返回 void 的函数,而第二种方法则不行。

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

要测试特定的错误消息:

检查异常内容

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.')));
于 2021-04-30T04:14:01.500 回答
1

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

expect(operations.lookupOrderDetails, throwsA(isA<MyCustErr>()));`
于 2021-02-22T08:32:19.427 回答
1

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

expect(() => yourOperation.yourMethod(),
      throwsA(const TypeMatcher<YourException>()));
于 2019-11-14T18:57:34.180 回答
0

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

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

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

它仍然使用Gunter的答案,非常好!

于 2019-10-09T18:44:45.050 回答