首页 > 解决方案 > Flutter:测试是否抛出了特定的异常

问题描述

简而言之,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));

标签: dartflutterflutter-test

解决方案


这应该做你想要的:

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

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


推荐阅读